Form validation not showing - javascript

I am trying to use some code from a form validation example and tailor it to my own form but it doesn't seem to be working. There is a message that is supposed to appear when a user enters a name,phone number or email incorrectly e.g 'please enter a valid name'.I don't understand javascript that well so am struggling to try and find the problem. There aren't any console problems if that helps it is probably a naming issue?
jsFiddle
HTML
<form>
<div class="formColumn2">
<label for="name">
<span class="textStyle">Full Name*</span><input type="text" id="name"><br>
<span id="nameMessage" class="message">You must have a valid name</span>
</label>
<label for="email"><span class="textStyle">Email*</span>
<input type="text" id="email"><br>
<span id="emailMessage" class="message">You must have a valid email</span>
</label>
<label for="phoneNumber">
<span class="textStyle">Phone Number*</span>
<input type="text" id="phoneNumber"><br>
<span id="phoneMessage" class="message">You must have a valid phone number</span>
</label>
<input type="submit" id="submit" value="Submit">
</div>
</form>
CSS
.textStyle {
width: 150px;
display: inline-block;
}
.formColumn2 {
margin-top:-80px;
margin-left: 50px;
}
select{
width:200px;
margin:10px 0;
}
input[type=text],
input[type=password]{
width:200px;
margin:10px 0;
}
.message{
display: none;
}
input[type=submit]{
background: #fff;
border: 1px solid black;
cursor: pointer;
}
input[type=text].error,
input[type=password].error{
border: 3px solid red;
color: red;
}
Javascript
var nameInput = document.querySelector('#name');
var emailInput = document.querySelector('#email');
var phoneInput = document.querySelector ('#phoneNumber');
function displayError(fieldname, message) {
var input_field = document.querySelector('#' + fieldname);
var error_box = document.querySelector('#' + fieldname + 'Message');
addClass (input_field, 'error');
error_box.style.display = 'block';
error_box.innerHTML = message;
}
function hideError(fieldname){
var input_field = document.querySelector('#'+fieldname);
var error_box = document.querySelector('#'+fieldname+'Message');
removeClass (input_field, 'error');
error_box.style.display = 'none';
}
function addClass(html_element,class_str) {
if(html_element.className.indexOf(class_str) == -1){
html_element.className += ' '+class_str;
}
}
function removeClass(html_element, class_str){
if(html_element.className.indexOf(class_str) != -1){
html_element.className = html_element.className.replace(class_str, '');
}
}
nameInput.onblur = function(){
if(!nameInput.value){
valid = false;
displayError('name', 'Please enter your name');
}else if(!isValidName(nameInput.value)){
valid = false;
displayError('name', 'That name has invalid characters');
}else{
hideError('name');
}
emailInput.onblur = function(){
if(!emailInput.value){
valid = false;
displayError('email', 'Please enter your email');
}else if(!isValidEmail(emailInput.value)){
valid = false;
displayError('email', 'The email field is invalid');
}else{
hideError('email');
}
}
phoneInput.onblur = function(){
if(!emailInput.value){
valid = false;
displayError('phone', 'Please enter your number');
}else if(!isValidEmail(emailInput.value)){
valid = false;
displayError('email', 'The phone number field is invalid');
}else{
hideError('phone');
}
}
submitButton.onclick = function(){
var valid = true;
return valid;
}
function isValidName(str){
var namePattern = new RegExp('^[a-zA-Z \s\'-]{1,}$');
return namePattern.test(str);
}
function isValidEmail(str) {
var emailPattern = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return emailPattern.test(str);
}

if you will use jQuery, it will be less complicated.
if that you need to use
$('.formClass').validate();
and in html
just put required in text fields, whom you want they not to be empty.
<form class="formCLass">
<input type="text" name="username" required/>
<input type="email" name="email" required/>
</form>

Related

how to sumbit form with addEventListener

I saw this code from the internet and I want to understand somethings - https://codepen.io/FlorinPop17/pen/OJJKQeK
And I try to POST form after all the parms are valid.
The valid is in the client browser (and also in server side).
I want after the all inputs are valid to POST the inputs to <form action="/postdata">
<div class="container">
<div class="header">
<h2>Create Account</h2>
</div>
<form id="form" class="form">
<div class="form-control">
<label for="username">Username</label>
<input type="text" placeholder="florinpop17" id="username" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Email</label>
<input type="email" placeholder="a#florin-pop.com" id="email" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password</label>
<input type="password" placeholder="Password" id="password"/>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<div class="form-control">
<label for="username">Password check</label>
<input type="password" placeholder="Password two" id="password2"/>
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<small>Error message</small>
</div>
<button>Submit</button>
</form>
JS -
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
form.addEventListener('submit', e => {
e.preventDefault();
checkInputs();
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
if(usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
} else {
setSuccessFor(username);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
} else if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
} else{
setSuccessFor(password2);
}
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
So, after checking the validity and make sure that all valid, then send a fetch request with POST method to /postdata with a body equal to object with inputs value.
const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
form.addEventListener('submit', e => {
e.preventDefault();
if (checkInputs()) {
fetch('/postdata', {
body: {
username: username.value,
email: email.value,
password: password.value,
password2: password2.value,
},
method: 'POST',
})
}
});
function checkInputs() {
// trim to remove the whitespaces
const usernameValue = username.value.trim();
const emailValue = email.value.trim();
const passwordValue = password.value.trim();
const password2Value = password2.value.trim();
let isValid = true
if(usernameValue === '') {
setErrorFor(username, 'Username cannot be blank');
isValid = false;
} else {
setSuccessFor(username);
}
if(emailValue === '') {
setErrorFor(email, 'Email cannot be blank');
isValid = false;
} else if (!isEmail(emailValue)) {
setErrorFor(email, 'Not a valid email');
} else {
setSuccessFor(email);
}
if(passwordValue === '') {
setErrorFor(password, 'Password cannot be blank');
isValid = false;
} else {
setSuccessFor(password);
}
if(password2Value === '') {
setErrorFor(password2, 'Password2 cannot be blank');
isValid = false;
} else if(passwordValue !== password2Value) {
setErrorFor(password2, 'Passwords does not match');
isValid = false;
} else{
setSuccessFor(password2);
}
return isValid;
}
function setErrorFor(input, message) {
const formControl = input.parentElement;
const small = formControl.querySelector('small');
formControl.className = 'form-control error';
small.innerText = message;
}
function setSuccessFor(input) {
const formControl = input.parentElement;
formControl.className = 'form-control success';
}
function isEmail(email) {
return /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(email);
}
Critical Details
There are a ton of changes to OP, but only a few changes are actually important. The <form> attributes should be as follows:
<form id="main" action="/postdata" method="POST">
The action value is a relative location, it's correct as long as the <form> is in the same domain as the server. Otherwise, it'll be something like: https://serverDomain.com/postData.
Next, the event handler triggered by the "submit" event needs to check each "div.form-control" to see if they all have the class: ".success" after the checkInputs() function runs. If they do, then the <form> needs to be submitted.
main.addEventListener('submit', function(e) {
e.preventDefault();
checkInputs();
if (Array.from(document.querySelectorAll(".form-control"))
.every(div => div.classList.contains("success"))) {
this.submit();
}
});
The example above should work with the OP unchanged. Note the anonymous event handler is not an arrow function. IMO arrow function event handlers are limiting because the keyword this is useless (see addEventListener, arrow functions, and `this`).
Other Changes
Although many things have changed from the OP in the example, fundamentally they are the same, it's just I wrote it a little better.
Some elements were changed into form controls which provided added features, made more easily accessible, and even better semantically.
<div class="form-control">
<!--from-
--to-->
<fieldset name="formControl">
<small>
<!--from-
--to-->
<output name="message">
HTMLFormElement and
HTMLFormControlsCollection interfaces are used to reference the <form> and it's form controls. The syntax is succinct and specialized so there's more control with less code.
Functions isUser() and isPass() are added to impose real criteria for username and password values.
The error() function (in OP it is setErrorFor()) has an third optional #param {string} criteria - which adds a <input type="button"> that opens a <dialog> that displays the given string criteria.
When the <form> is successfully submitted, the data is sent to a live test server. The response is captured and displayed in the <iframe> located at the bottom of the page.
const main = document.forms.main;
const fc = main.elements;
const user = fc.username;
const email = fc.email;
const pass = fc.password;
const check = fc.check;
const details = fc.details;
const modal = details.parentElement;
main.addEventListener('submit', function(e) {
e.preventDefault();
checkInputs();
if (Array.from(fc.formControl).every(fSet => fSet.classList.contains("valid"))) {
this.submit();
}
});
main.addEventListener("click", function(e) {
const clicked = e.target;
if (clicked !== this) {
if (clicked.name === "more") {
modal.showModal();
details.value = clicked.dataset.text;
}
if (clicked.id === "close") {
modal.close();
}
}
});
function checkInputs() {
const userData = user.value.trim();
const emailData = email.value.trim();
const passData = pass.value.trim();
const checkData = check.value.trim();
if (userData === "") {
error(user, "Username is blank, enter data");
} else if (!isUser(userData)) {
error(user, "Username must have at least 8 characters", "A minimum of 8 characters in any combination of lower case letters, upper case letters, and digits");
} else {
valid(user);
}
if (emailData === "") {
error(email, "Email is blank, enter data");
} else if (!isEmail(emailData)) {
error(email, "Email address is invalid", "Email address must have 1 or more characters, an ampersand: #, followed by 1 or more charaters, a dot: ., followed by 1 or more characters");
} else {
valid(email);
}
if (passData === "") {
error(pass, "Password is blank, enter data");
} else if (!isPass(passData)) {
error(pass, "Password must have at least 8 character", "Password must have a minimum of 8 characters with at least 1 lower case letter, 1 upper case letter, 1 digit, and 1 symbol (!, #, #, $, %, ^, &, *, _, =, +, -)");
} else {
valid(pass);
}
if (checkData === "") {
error(check, "Password check is blank, enter data");
} else if (passData !== checkData) {
error(check, "Passwords do not match");
} else {
valid(check);
}
}
function error(input, message, criteria) {
const set = input.parentElement;
const msg = set.elements.message;
set.classList.add('error');
set.classList.remove('valid');
msg.value = message;
if (criteria) {
msg.insertAdjacentHTML("beforeend", `<input name="more" class="more" type="button" value="..." data-text="${criteria}">`);
}
}
function valid(input) {
const set = input.parentElement;
const msg = set.elements.message;
set.classList.add('valid');
set.classList.remove('error');
msg.value = "";
}
function isUser(name) {
const rgx = /[a-zA-Z0-9]{8,}/g;
return rgx.test(name);
}
function isEmail(address) {
const rgx = /\S+#\S+\.\S+/g;
return rgx.test(address);
}
function isPass(secret) {
const rgx = /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{8,}$/g;
return rgx.test(secret);
}
#import url('https://fonts.googleapis.com/css?family=Open+Sans:400,500&display=swap');
* {
box-sizing: border-box;
}
html {
font: 400 2ch/1.15 'Open Sans'
}
body {
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
background: #9b59b6;
}
form {
padding: 30px 40px;
}
fieldset {
position: relative;
margin-bottom: 15px;
border: 0;
}
label {
display: inline-block;
margin-bottom: 5px;
color: #fff;
}
.data {
display: block;
width: 100%;
padding: 10px;
border: 2px solid #f0f0f0;
border-radius: 4px;
font: inherit;
}
.data:focus {
border-color: #777;
outline: 0;
}
.success .data {
border-color: #2ecc71;
}
.error .data {
border-color: #e74c3c;
}
i {
position: absolute;
top: 42px;
right: 15px;
visibility: hidden;
}
.valid i.fa-check-circle {
color: #2ecc71;
visibility: visible;
}
.error i.fa-exclamation-circle {
color: #e74c3c;
visibility: visible;
}
output {
display: inline-block;
position: absolute;
bottom: -15px;
left: 15px;
padding: 4px;
border-radius: 4px;
font-size: 0.75rem;
color: #e74c3c;
background: #fff;
visibility: hidden;
}
button {
display: block;
width: 100%;
margin: 20px auto;
padding: 10px;
border: 2px solid #8e44ad;
border-radius: 4px;
color: #fff;
font: inherit;
background: #8e44ad;
cursor: pointer;
}
.more {
position: absolute;
top: -1px;
right: -1.75rem;
padding-bottom: 3px;
cursor: pointer;
visibility: hidden;
}
.error output,
.error .more {
visibility: visible;
}
#details {
position: static;
margin-bottom: 10px;
visibility: visible;
}
#close {
float: right;
cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" rel="stylesheet">
<form id="main" action="https://httpbin.org/post" method="POST" target="response">
<fieldset name="formControl">
<label for="username">Username</label>
<input id="username" name="username" class="data" type="text" placeholder="user01" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<fieldset name="formControl">
<label for="email">Email</label>
<input id="email" name="email" class="data" type="text" placeholder="user01#email.com" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<fieldset name="formControl">
<label for="password">Password</label>
<input id="password" name="password" class="data" type="password" placeholder="Password" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<fieldset name="formControl">
<label for="check">Password Check</label>
<input id="check" name="check" class="data" type="password" placeholder="Password as entered previously" />
<i class="fas fa-check-circle"></i>
<i class="fas fa-exclamation-circle"></i>
<output name="message"></output>
</fieldset>
<button>Submit</button>
<iframe name="response"></iframe>
<dialog>
<output id="details"></output>
<input id="close" type="button" value="OK">
</dialog>
</form>

eventListener works on click 1. But fails on click 2

So i am making a signup form with action="signup.inc.php" But im handling the validation in javascript.
If the fields are empty or the password don't match the input gets a red border and the placeholder is replaced.
This works perfectly on the first click. But as soon as i click again he just shoots to signup.inc.php.
I need those validations to be done before we go to the signup.inc.php file.
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
let result = false;
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
inputArr.forEach(function (input){
if (input.value.trim() === ''){
showError(input, 'this field is required');
} else {
showSucces(input);
result = true;
}
});
}
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
} else {
result = true;
}
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e){
if (result !== true) {
requiredFields ([firstname, lastname, email, username, password, passwordRepeat]);
matchPasswords (password, passwordRepeat);
e.preventDefault();
} else {
result = true;
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
Your problem is that if any of the inputs are valid, result is set to true and so on the next submit the inputs are not checked and the form submits. You can work around that by always testing all the inputs, returning the error status from each input checking function and checking that they all return true:
let signupForm = document.getElementById('signupForm');
let firstname = document.getElementById('firstname');
let lastname = document.getElementById('lastname');
let email = document.getElementById('email');
let username = document.getElementById('username');
let password = document.getElementById('password');
let passwordRepeat = document.getElementById('passwordRepeat');
function showError(input, message) {
let formControl = input.parentElement;
formControl.className = 'formControl error';
let error = input;
error.placeholder = message;
}
function showSucces(input) {
let formControl = input.parentElement;
formControl.className = 'formControl succes';
}
function requiredFields(inputArr) {
result = true;
inputArr.forEach(function(input) {
if (input.value.trim() === '') {
showError(input, 'this field is required');
result = false;
} else {
showSucces(input);
}
});
return result;
}
function matchPasswords(input1, input2) {
result = true;
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
result = false;
}
return result;
}
/* Eventlistener */
signupForm.addEventListener('submit', function(e) {
let result = true;
result = result && requiredFields([firstname, lastname, email, username, password, passwordRepeat]);
result = result && matchPasswords(password, passwordRepeat);
if (!result) {
e.preventDefault();
}
});
.signupFormWrap {
margin-bottom: 15px;
}
.signupFormWrap,
.formControl {
width: 400px;
display: flex;
flex-direction: column;
}
.formControl label {
font-size: 1.2rem;
}
.formControl>input[type=text],
input[type=email],
input[type=password] {
padding-left: 10px;
font-size: 1rem;
line-height: 1.8;
}
.button {
margin-top: 15px;
margin-bottom: 15px;
}
.formControl.error>input {
border: 1px solid red;
}
.formControl.succes>input {
border: 1px solid green;
}
<form name="signupForm" id="signupForm" action="assets/php/signup.inc.php" method="POST">
<div class="signupFormWrap">
<div class="formControl">
<label for="firstname">Firstname</label>
<input type="text" name="firstname" id="firstname" placeholder="Fill in your firstname here..">
</div>
<div class="formControl">
<label for="lastname">lastname</label>
<input type="text" name="lastname" id="lastname" placeholder="Fill in your lastname here..">
</div>
<div class="formControl">
<label for="email">Email</label>
<input type="email" name="email" id="email" placeholder="Fill in your email here..">
</div>
<div class="formControl">
<label for="username">Username</label>
<input type="text" name="username" id="username" placeholder="Fill in your username here..">
</div>
<div class="formControl">
<label for="password">Password</label>
<input type="password" name="password" id="password" placeholder="fill in your password here..">
</div>
<div class="formControl">
<label for="passwordRepeat">Verify your password</label>
<input type="password" name="passwordRepeat" id="passwordRepeat" placeholder="Verify your password">
</div>
<button type="submit" name="submit" class="button">Sign up</button>
</div>
</form>
change all validation functions like
function matchPasswords(input1, input2) {
if (input1.value !== input2.value) {
showError(input2, "These passwords don't match");
return false;
}
return true;
}
signupForm.addEventListener('submit', function(e){
if(!requiredFields ([firstname, lastname, email, username, password, passwordRepeat]) &&
!matchPasswords (password, passwordRepeat)){
e.preventDefault();
}
});

Javascript cannot submit form with empty field validation

I have a small issue with my code not submitting my form. Once I fill out the form and press the submit button, nothing simply happens, it seems like the form is not being submitted. In practice, this code should check whether there are any empty fields and if so, it prompts a message instructing to fill out the fields. If every field filled out, submit the form.
function storeUser() {
var userObject = {};
userObject.username = document.getElementById("username").value;
userObject.email = document.getElementById("inputEmail").value;
userObject.password = document.getElementById("inputPassword").value;
userObject.passwordConfirm = document.getElementById("inputPasswordConfirm").value;
userObject.mobileNumber = document.getElementById("inputNumber").value;
userObject.score = 0;
if (userObject.password !== userObject.passwordConfirm) {
document.getElementById("Warning").innerHTML = "Your password doesn't match.";
return false;
}
if (userObject.username === "") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.email === " " ) {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.password === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.passwordConfirm === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
}
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
As you most probably noticed, I'm a complete novice to this. Aynone could lead me the right way?
EDIT:
<form class="form-container" name="registerForm" onsubmit="return false">
<p><b>Please fill out all fields to register your account</b></p>
<div class="form-group">
<input type="text" class="form-control" id="username" aria-describedby="username" placeholder="Username" minlength=3 required>
</div>
<div class="form-group">
<input type="email" class="form-control" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPassword" placeholder="Password" required>
</div>
<div class="form-group">
<input type="password" class="form-control" id="inputPasswordConfirm" placeholder="Confirm password" required>
</div>
<div class="form-group">
<input type="tel" class="form-control" id="inputNumber" placeholder="Mobile number" pattern="^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$" required>
</div>
<button type="submit" onclick="storeUser()" class="btn btn-primary regstrbtn">Register</button>
<p id="Result"></p>
<p id="Warning" style="color: red;"></p>
</form>
Looking at your code I found a number of problems:
Invalid telephone number regexp: you are using the following regexp to validate the telephone number field, but it has a missing character:
^\s*\(?(020[7,8]{1}\)?[ ]?[1-9]{1}[0-9{2}[ ]?[0-9]{4})|(0[1-8]{1}[0-9]{3}\)?[ ]?[1-9]{1}[0-9]{2}[ ]?[0-9]{3})\s*$
// missing ] after 0-9 ^^
(I am going to ignore the fact that the regular expression has placeholder 'Mobile number' yet only accepts landline phone numbers for inner and outer London in the UK.)
You are showing validation error messages if the email, password, confirm-password and telephone number fields contain a single space:
if (userObject.email === " " ) {
You probably want to be comparing the values against an empty string instead:
if (userObject.email === "" ) {
The end of your storeUser() function is as follows:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
else {
return true;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
When do we reach the last two lines, the one that writes to local storage and the one that shows the success message?
If the telephone number field contains a single space, then a warning message appears and the function returns false.
If the telephone number field contains anything other than a single space, the function returns true.
The last two lines are unreachable. They are never executed because the function returns before it gets to them.
What you probably want to do is to get rid of the else clause and add return true; at the bottom, i.e.:
if (userObject.mobileNumber === " ") {
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
return false;
}
localStorage[userObject.email] = JSON.stringify(userObject);
document.getElementById("Result").innerHTML = "Success! You have registered your account.";
return true;
Inconsistent use of return false;. If the passwords don't match, or the telephone number field isn't filled out, the function returns false. There is no corresponding return false; line for the username, email, password and confirm-password fields. Add this line for each of these fields.
You aren't clearing the warning message if the form is successfully completed. Add the line
document.getElementById("Warning").innerHTML = "";
to the end of your function.
Incidentally you have various pairs of lines
document.getElementById("Warning").innerHTML = "";
document.getElementById("Warning").innerHTML = "Please fill out the form fully!";
but the first line in each pair is unnecessary because the empty-string value you assign to the inner HTML of the warning element is immediately replaced by the warning message assigned in the second line. You can delete the first line of each such pair.
You can simply manage this using HTML5 form field validators, please find below code snippet:
body {
font-family: Helvetica, Arial;
font-size:12px;
}
h1 {
font-size:200%;
}
legend {
padding:0 5px;
text-align:right;
}
fieldset > div {
margin:10px 0;
}
fieldset > legend + div {
margin-top:0;
}
fieldset > div:last-child {
margin-bottom:0;
}
label {
display:inline-block;
width:100px;
}
input {
width:200px;
}
input[type="number"] {
width:30px;
}
div > input[type="submit"] {
background: #ccc;
border:1px solid #999;
width:auto;
}
input:required {
background:hsl(180, 50%, 90%);
border:1px solid #999;
}
input:optional {
background:hsl(300, 50%, 90%);
border:1px dotted hsl(180, 50%, 90%);
}
input:valid,
input:in-range {
background:hsl(120, 50%, 90%);
border-color:hsl(120, 50%, 50%);
}
input:invalid,
input:out-of-range {
border-color:hsl(0, 50%, 50%);
background:hsl(0, 50%, 90%);
}
.help {
display:none;
font-size:90%;
}
input:focus + .help {
display:inline-block;
}
div.submit {
margin-left:100px;
}
<form action="" method="post">
<fieldset>
<legend>Booking Details</legend>
<div>
<label for="name">Name:</label>
<input id="name" name="name" value="" required pattern="[A-Za-z-0-9]+\s[A-Za-z-'0-9]+" title="firstname lastname" aria-required="true" aria-describedby="name-format">
<span id="name-format" class="help">Format: firstname lastname</span>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" value="" required aria-required="true">
</div>
<div>
<label for="website">Website:</label>
<input type="url" id="website" name="website" value="">
</div>
<div>
<label for="numTickets"><abbr title="Number">No.</abbr> of Tickets:</label>
<input type="number" id="numTickets" name="numTickets" value="" required aria-required="true" min="1" max="4">
</div>
<div class="submit">
<input type="submit" value="Submit">
</div>
</fieldset>
</form>

Validating contact form with javascript

The code below obviously has a lot of errors or some other things missing but I am beginner to JavaScript trying to make my own projects.
I tried to make this contact form with JavaScript validation from my own and a bit with a search but I'm stuck because validation form doesn't work at all. I would appreciate if you help me fixing this, thank you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Well, you only defined validation methods but don't use them, that's why they have no effect.
You should add event listeners like onchange (or oninput, depending on when you'd like to show error messages) to your fields.
For instance:
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
Actually, you have multiple more problems:
error is undefined: you should create another element and find it in JS
you have to use element.value, not element to access a value of input
you have undefined characters used in a weird way in your checks; to check the length of content, use element.value.length
Here's a snippet with these fixes:
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('.error');
function validateName() {
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName()">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail()">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Moreover, I'd make some more improvements to the code, namely
use event.target inside event handlers instead of calcing the elements globally (note the difference in usage inside html too);
clear the error div when the content is ok!
why multiple return false instead of one in the end of the handler?
you don't use the submit variable, get rid of it; does submitForm do anything useful? (submits on submit??) Not sure, but it seems it should be removed, too
let error = document.querySelector('.error');
function validateName(event) {
let name = event.target;
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
} else {
error.innerHTML = '';
}
return false;
}
function validateEmail(event) {
let email = event.target;
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
} else {
error.innerHTML = '';
}
return false;
}
function submitForm() {
document.querySelector('.submit').submit();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input class="name" type="text" placeholder="Your Name" onchange="validateName(event)">
<br>
<input class="email" type="email" placeholder="Your Email" onchange="validateEmail(event)">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<div class="error"></div>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>
Alot of your syntax and validation methods are off. Few tips: you need to use name.value and email.value to get the values of the elements, you also need to use name.value.length instead of email < characters.length < 5 and change the button type to submit and you can negate having to call it in JS.
Below is a working snippet based on the code you posted. I believe it does what you want.
let error = document.getElementById('error');
function validateName() {
let name = document.getElementById('name');
if (!name.value) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters on name';
return false;
}
}
function validateEmail() {
let email = document.getElementById('email');
if (!email.value) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 5 characters on email';
return false;
}
}
function submitForm() {
error.innerHTML = ""
validateEmail()
validateName()
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<input id="name" type="text" placeholder="Your Name">
<br>
<input id="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" type = "submit" action="/submit.php" onclick="submitForm()">Submit</button>
<div id="error">
</div>
</div>
</div>
You've written your JS function validateName and validateEmails but you aren't calling those functions anywhere. Instead of selecting the .submit button inside of submitForm(), call those functions. The line you have inside of submitForm is doing nothing. onclick() within your HTML handles the calling of the function submitForm(), and submitForm() should then validate your form.
Edit: you can also call validateName and validateEmails when the email or name fields are edited.
Yeah, like what the other contributors said, the validate functions are written well, they just aren't being called.
You can either add them to the onchange property of your input elements, or call it in your submitform function like so:
function validateName() {
if (name === null) {
error.innerHTML = 'Name cannot be blank';
return false;
} else if (name < characters.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
return true;
}
function validateEmail() {
if (email === null) {
error.innerHTML = 'Email cannot be blank';
return false;
} else if (email < characters.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
return true;
}
function submitForm(){
if(validateName() && validateEmail()){
//Do whatever submitting entails
}
}
Also remember to add an error div to your html to display the errors, and to create an error querySelector variable like you did with name, email and submit.
You're doing great! Keep up the good work!
Here's something that works to a minimum using your current code. I added comments to explain what is going on. Don't hesitate to ask me for any clarifications. Like you said, code can be improved further but I didn't want to change too much and confuse you.
let name = document.querySelector('.name');
let email = document.querySelector('.email');
let submit = document.querySelector('.submit');
let error = document.querySelector('#error'); //Get's the span in the html where the errors will be shown.
function validateName() {
//Get the text value of name with name.value and care with an empty string.
if (name.value === "") {
error.innerHTML = 'Name cannot be blank';
return false;
//Get the number of character in the value of the name and see if you have less than 3.
} else if (name.value.length < 3) {
error.innerHTML = 'Use more than 3 characters';
return false;
}
}
function validateEmail() {
//Get the text value of name with name.value and compare with an empty string.
if (email.value === "") {
error.innerHTML = 'Email cannot be blank';
return false;
//Get the number of characters in the value of the email and see if you have less than 5.
} else if (email.value.length < 5) {
error.innerHTML = 'Use more than 3 characters on email';
return false;
}
}
function submitForm() {
//Instead of calling the function .submit (that doesn't exist). Call the verification functions that you made.
validateName();
validateEmail();
}
.info {
display: flex;
justify-content: center;
padding-top: 20px;
text-align: center;
background-color: mediumslateblue;
font-size: 22px;
}
.name {
margin-top: 10px;
}
.email {
margin-top: 10px;
}
.mesage {
margin-top: 10px;
}
.submit {
margin-bottom: 10px;
}
<div class="info">
<div class="info-form">
<span id="error"></span>
<input class="name" type="text" placeholder="Your Name">
<br>
<input class="email" type="email" placeholder="Your Email">
<br>
<textarea name="message" class="mesage" cols="36" rows="3" placeholder="Your message"></textarea>
<br>
<button class="submit" action="/submit.php" onclick="submitForm()">Submit</button>
</div>
</div>

How to set div modal's closing button ? How make the closing button function work in javascript?

I have created an email registration form with the help of html, css and javascript. The problem which i am facing is that i have included div modal code from W3schools. The Modal is working properly but the close button is not working or set accordingly. Can anybody please help me in this issue? I am struggling on this issue for past 3 days but i am not able to solve this issue. This is the screenshot where the problem is coming?
function formValidation() {
var username = document.getElementById('username');
var email = document.getElementById('email');
var password = document.getElementById('password');
var address = document.getElementById('address');
var phoneno = document.getElementById('phoneno');
// if(username.value.length == 0){
// document.getElementById('head').innerText = "* All fields are mandatory *";
// username.focus();
// return false;
// }
let statususername = validateUsername(username, "* Username should be in proper format. *");
let statusemail = ValidateEmail(email, "* Email should be in proper format *");
let statuspassword = validatePassword(password, "* Password should be in 7-10 characters with one word in capitalization and numerical digits should be there*");
let statusaddress = alphanumeric(address, "*Address should be in proper format.*");
let statusphone = allnumeric(phoneno, "*Phone no. should be in numbers only.*");
console.log(statususername);
console.log(statusemail);
console.log(statuspassword);
console.log(statusaddress);
console.log(statusphone);
if (statusFistName && statusLastName && statusClass && statusRollNo && statusEmail) return true;
else return false;
}
function validateUsername(inputtext, alertMsg) {
var alphabetsExp = /\W/;
if (inputtext.value.match(alphabetsExp)) {
document.getElementById('d1').innerText = '';
return true
} else {
document.getElementById('p1').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function validatePassword(inputtext, alertMsg) {
// Validate lowercase letters
var lowerCaseLetters = /[a-z]/g;
if (myInput.value.match(lowerCaseLetters)) {
letter.classList.remove("invalid");
letter.classList.add("valid");
} else {
letter.classList.remove("valid");
letter.classList.add("invalid");
}
var upperCaseLetters = /[A-Z]/g;
if (myInput.value.match(upperCaseLetters)) {
capital.classList.remove("invalid");
capital.classList.add("valid");
} else {
capital.classList.remove("valid");
capital.classList.add("invalid");
}
// Validate numbers
var numbers = /[0-9]/g;
if (myInput.value.match(numbers)) {
number.classList.remove("invalid");
number.classList.add("valid");
} else {
number.classList.remove("valid");
number.classList.add("invalid");
}
// Validate length
if (myInput.value.length >= 8) {
length.classList.remove("invalid");
length.classList.add("valid");
} else {
length.classList.remove("valid");
length.classList.add("invalid");
}
document.getElementById('d3').innerText = alertMsg;
inputtext.focus();
return false;
}
function allnumeric(inputtext, alertMsg) {
var numeric = /^[0-9]+$/;
if (inputtext.value.match(numeric)) {
document.getElementById('d5').innerText = '';
return true;
} else {
document.getElementById('d5').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function alphanumeric(inputtext, alertMsg) {
var alpha = /^[0-9a-zA-Z]+$/;
if (inputtext.value.match(alpha)) {
document.getElementById('d4').innerText = '';
return true;
} else {
document.getElementById('d4').innerText = alertMsg;
inputtext.focus();
return false;
}
}
function ValidateEmail(inputtext, alertMsg) {
var emailExp = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (inputtext.value.match(emailExp)) {
document.getElementById('d2').innerText = '';
return true;
} else {
document.getElementById('d2').innerText = alertMsg;
inputtext.focus();
return false;
}
}
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var button = document.getElementById('submit');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
function test() {
var modal = document.getElementById('myModal');
var mytext = document.getElementById('mytext');
var span = document.getElementsByClassName("close")[0];
modal.style.display = "block";
modal.style.display = "none";
// if (event.target == modal) {
// modal.style.display = "none";
// }
var username = document.getElementById('username');
var email = document.getElementById('email');
var password = document.getElementById('password');
var address = document.getElementById('address');
var phoneno = document.getElementById('phoneno');
str = 'Hello ' + username.value + ', Your email address is ' + email.value + ', Your Email Address is successfully registered.';
//document.getElementById('myModal').innerHTML = 'Username : ' + username.value + '<br>Email : ' + email.value + '<br>password : ' + password.value + '<br>Address : ' + address.value + '<br>Phone No. : ' + phoneno.value;
mytext.innerHTML = str;
}
// function show() {
// var username = document.getElementById('username');
// var email = document.getElementById('email');
// var password = document.getElementById('password');
// var address = document.getElementById('address');
// var phoneno = document.getElementById('phoneno');
// // test validation
// let isValidated = formValidation();
// if (isValidated) {
// console.log('Validation successful');
// return str = 'Hello ' + username.value + email.value + ', Your email address is' + phoneno.value + ', You have successfully registered for this course';
// document.getElementById('myModal').innerHTML = 'Username : ' + username.value + '<br>Email : ' + email.value + '<br>password : ' + password.value + '<br>Address : ' + address.value + '<br>Phone No. : ' + phoneno.value;
// } else console.log('Verificatio failed');
// }
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.4);
/* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form class="form-horizontal">
<fieldset>
<legend>
<center>Email Registration Form</center>
</legend>
<div class="form-group">
<label class="col-md-4 control-label" for="username">Username</label>
<div class="col-md-4">
<input id="username" name="username" type="text" placeholder="Username" class="form-control input-md" value="admin234">
<p id="d1"></p>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="email">Email</label>
<div class="col-md-4">
<input id="email" name="email" type="email" placeholder="Email" class="form-control input-md" value="admin#gmail.com">
<p id="d2"></p>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="password">Password</label>
<div class="col-md-4">
<input id="password" name="password" type="password" placeholder="Password" class="form-control input-md" value="abc123456">
<p id="d3"></p>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="address">Address</label>
<div class="col-md-4">
<input id="address" name="address" type="text" placeholder="Address" class="form-control input-md" value="#822, Sector 7, Chandigarh.">
<p id="d4"></p>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="phoneno">Phone No</label>
<div class="col-md-4">
<input id="phoneno" name="phoneno" type="text" placeholder="Phone No" class="form-control input-md" value="938322219">
<p id="d5"></p>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="submit"></label>
<div class="col-md-4">
<button id="submit" type="button" onclick="test()" name="submit" class="btn btn-success">Submit</button>
</div>
</div>
</div>
</div>
</div>
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<p id="mytext"></p>
<span class="close">×</span>
</div>
</div>
</fieldset>
</form>

Categories

Resources