I have created five input fields and a submit button to validate that fields but somehow it is not validated on submit.
In my JS I print the error dynamically. I have debugged by code and I get the proper values and errors, but it doesn't displays dynamically.
function seterror(id, error) {
// set error
var element = document.getElementById(id);
debugger;
console.log(element);
element.getElementsByClassName('ferror')[0].innerHTML = error;
}
function validateForm(e) {
e.preventDefault();
var returnval = true;
var name = document.forms['myForm']['fname'].value;
if (name.length < 5) {
seterror("uname", "abc");
returnval = false;
}
return returnval;
}
.ferror {
color: red;
}
<h1>Form Validation Demo</h1>
<form onsubmit="return validateForm()" name="myForm">
Name*: <input type="text" id="uname" name="fname"><b><span class="ferror"></span></b><br> Password*: <input type="password" id="pass" name="fpass"><b><span class="ferror"></span></b><br> Confirm Password*: <input type="password" id="cpassword" name="fcpass"><b><span class="ferror"></span></b> <br> Email*: <input type="email" id="uemail" name="femail"><b><span class="ferror"></span></b> <br> Phone*:
<input type="phone" id="uphone" name="fphone"><b><span class="ferror"></span></b> <br>
<input type="submit" class="btn" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Given all the comments under the question, here's my suggestion for a more flexible remake:
Don't use IDs for your fields
Use an additional <label> as wrapper
Don't bloat HTML with useless empty <span> error elements - create them using JS
Use a proper addEventListener() and use its Event in the Validation function
Use an errors array to store all the errors during each part of the validation
Only at the end, if the errors Array has items in it (meaning something is invalid) - in that case use Event.preventDefault() to prevent the form being submitted.
// Utility functions:
const EL = (sel, parent) => (parent || document).querySelector(sel);
const ELS = (sel, parent) => (parent || document).querySelectorAll(sel);
const ELNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Form validation script:
const EL_form = EL("#myForm");
const validateForm = (evt) => {
// Remove old errors
ELS(".ferror", EL_form).forEach(el => el.remove());
// Prepare an array to hold your errors
const errors = [];
// Get the desired fields:
const EL_fname = EL('[name="fname"]', EL_form);
const EL_fpass = EL('[name="fpass"]', EL_form);
const EL_fcpass = EL('[name="fcpass"]', EL_form);
const EL_femail = EL('[name="femail"]', EL_form);
const EL_fphone = EL('[name="fphone"]', EL_form);
// Validation and errors:
if (EL_fname.value.trim().length <= 4) {
errors.push({name: "fname", text: "Name is too short (min 4 chars)"});
}
if (EL_fpass.value.trim().length <= 8) {
errors.push({name: "fpass", text: "Password is too short (min 8 chars)"});
}
if (EL_fpass.value !== EL_fcpass.value) {
errors.push({name: "fcpass", text: "Passwords do not match"});
}
if (!/^.+#.+\./.test(EL_femail.value)) {
errors.push({name: "femail", text: "Invalid Email address"});
}
if (EL_fphone.value.trim().replace(/\D/g, "").length <= 6) {
errors.push({name: "fphone", text: "Invalid telephone number"});
}
// Show errors:
errors.forEach(err => {
const EL_error = ELNew("span", {
className: "ferror",
textContent: err.text,
});
EL(`[name="${err.name}"]`, EL_form).closest("label").append(EL_error);
});
// Prevent Form subnit on any error
if (errors.length) {
evt.preventDefault();
}
};
EL_form.addEventListener("submit", validateForm);
form label {
display: block;
}
.ferror {
color: red;
font-weight: 700;
}
<form id="myForm">
<label>Name: <input name="fname" type="text"></label>
<label>Password: <input name="fpass" type="password"></label>
<label>Confirm Password: <input name="fcpass" type="password"></label>
<label>Email: <input name="femail" type="email"></label>
<label>Phone: <input name="fphone" type="phone"></label>
<br>
<input type="submit" class="btn" value="Submit">
</form>
Related
I am creating a JavaScript form with validation. It is functional on first data entry into the form, however, once you correctly receive a data validation error for an incorrect input, then the functionality stops, the submit button stays locked and I do not know how to undo it.
I have used the ".preventDefault()" to stop inputs going through, but I do not know how to undo this method after a data validation error has already been given.
client-side-form-validation.js
const signupForm = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const emailError = document.getElementById('email-error');
const passwordError = document.getElementById('password-error');
// Email field client side form validation
signupForm.addEventListener('submit', (e) => {
let emailMessages = []
if (email.value === '' || email.value == null){
emailMessages.push('Email is required')
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email.value)){
emailMessages.push('Email is invalid')
}
if(emailMessages.length > 0){
e.preventDefault()
emailError.innerHTML = emailMessages.join('<br>')
}
});
// Password field client side form validation
signupForm.addEventListener('submit', (e) => {
let passwordMessages = []
if (password.value === '' || password.value == null){
passwordMessages.push('Password is required')
}
if(passwordMessages.length > 0){
e.preventDefault()
passwordError.innerHTML = passwordMessages.join('<br>')
}
});
signup.ejs
<form id="signup-form" action='/signup' method="post">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<div class="signup-error" id="email-error"></div>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<div class="signup-error" id="password-error"></div>
<input type="submit" value="Submit">
</form>
Thanks for your time :)
I played around with the code for a little and came up with my own answer.
My answer involved attaching a else statement to the if statements, deleting the array and then posting the deleted array to the error message in the form.
if(emailMessages.length > 0){
e.preventDefault();
emailError.innerHTML = emailMessages.join('<br>');
}else{
delete emailMessages;
emailError.innerHTML = emailMessages.join('<br>');
}
Then do the same for the password validation.
It seems to work here.
Update: made it more friendly by checking the error on change as well as on submit.
const signupForm = document.getElementById('signup-form');
const email = document.getElementById('email');
const password = document.getElementById('password');
const emailError = document.getElementById('email-error');
const passwordError = document.getElementById('password-error');
signupForm.addEventListener('submit', (e) => {
if (!validate_email()) {
e.preventDefault()
}
if (!validate_password()) {
e.preventDefault()
}
// continue to submit
});
email.addEventListener('change', validate_email);
password.addEventListener('change', validate_password);
function validate_email() {
let messages = []
if (email.value === '' || email.value == null) {
messages.push('Email is required')
}
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(email.value)) {
messages.push('Email is invalid')
}
var valid = !messages.length;
emailError.innerHTML = valid ? "" : messages.join('<br>')
return valid;
}
function validate_password() {
let messages = []
if (password.value === '' || password.value == null) {
messages.push('Password is required')
}
var valid = !messages.length;
passwordError.innerHTML = valid ? "" : messages.join('<br>')
return valid;
}
.signup-error {
color: red;
}
.form-group {
margin-bottom: 10px;
}
<form id="signup-form" action='/signup' method="post">
<div class="form-group">
<label for="email">Email:</label><br>
<input type="text" id="email" name="email"><br>
<div class="signup-error" id="email-error"></div>
</div>
<div class="form-group">
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<div class="signup-error" id="password-error"></div>
</div>
<input type="submit" value="Submit">
</form>
I would like to show tick simple when the field is filled correctly, and show error message when it is not filled on each field.
I tried to make the code which using function validateForm, but it did not work. How do I fix the code? Please teach me where to fix.
Here is my html code
<form>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Name</p>
<input type="text"id="name">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required" >Required</span>Number</p>
<input type="text" id="number">
</div>
<div class="Form-Item">
<p class="Form-Item-Label"><span class="Form-Item-Label-Required">Required</span>Mail address</p>
<input type="email">
</div>
<div class="Form-Item">
<p class="Form-Item-Label isMsg"><span class="Form-Item-Label-Required">Required</span>Message</p>
<textarea id="text"></textarea>
</div>
<input type="submit" value="submit">
<p id="log"></p>
</form>
Here is my JavaScript code
function validateForm(e) {
if (typeof e == 'undefined') e = window.event;
var name = U.$('name');
var number = U.$('number');
var email = U.$('email');
var text = U.$('text');
var error = false;
if (/^[A-Z \.\-']{2,20}$/i.test(name.value)) {
removeErrorMessage('name');
addCorrectMessage('name', '✔');
} else {
addErrorMessage('name', 'Please enter your name.');
error = true;
}
if (/\d{3}[ \-\.]?\d{3}[ \-\.]?\d{4}/.test(number.value)) {
removeErrorMessage('number');
addCorrectMessage('number', '✔');
} else {
addErrorMessage('number', 'Please enter your phone number.');
error = true;
}
if (/^[\w.-]+#[\w.-]+\.[A-Za-z]{2,6}$/.test(email.value)) {
removeErrorMessage('email');
addCorrectMessage('email', '✔');
} else {
addErrorMessage('email', 'Please enter your email address.');
error = true;
}
if (/^[A-Z \.\-']{2,20}$/i.test(text.value)) {
removeErrorMessage('text');
addCorrectMessage('text', '✔');
} else {
addErrorMessage('text', 'Please enter your enquiry.');
error = true;
}
if (error) {
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
return false;
}
}
function addErrorMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Error';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'error';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'error';
}
}
function addCorrectMessage(id, msg) {
'use strict';
var elem = document.getElementById(id);
var newId = id + 'Correct';
var span = document.getElementById(newId);
if (span) {
span.firstChild.value = msg;
} else {
span = document.createElement('span');
span.id = newId;
span.className = 'Correct';
span.appendChild(document.createTextNode(msg));
elem.parentNode.appendChild(span);
elem.previousSibling.className = 'Correct';
}
}
function removeErrorMessage(id) {
'use strict';
var span = document.getElementById(id + 'Error');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
function removeCorrectMessage(id) {
'use strict';
var span = document.getElementById(id + 'Correct');
if (span) {
span.previousSibling.previousSibling.className = null;
span.parentNode.removeChild(span);
}
}
Using jQuery, you can use the .submit() event on a form element to conduct your own validation, note that you will have to preventDefault() to prevent the form submitting.
$("#myform").submit((e) => {
e.preventDefault(e);
// Validate name.
const name = $("#name").val();
if (name.length === 0) {
alert("Please provide a name!");
return;
}
alert("Success!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myform">
<input type="text" id="name" placeholder="John Doe" />
<button type="submit">Submit</button>
</form>
which npm package do u use to validate ur data?.
If u use "validator" (link: https://www.npmjs.com/package/validator)
You can check if the field is filled correctly and send a check mark to the user.
for example if u wanted to check if data is an email
const validator = require("validator");
validator.isEmail('foo#bar.com');
if u want to see more about the options for the field just check the npm package page
Modern Browser support the Constraint Validation API which provides localized error messages.
Using this you can easily perform validation during basic events. For example:
// this will prevent the form from submit and print the keys and values to the console
document.getElementById("myForm").onsubmit = function(event) {
if (this.checkValidity()) {
[...new FormData(this).entries()].forEach(([key, value]) => console.log(`${key}: ${value}`);
event.preventDefault();
return false;
}
}
Would print all fields which would've been submitted to the console.
Or on an input field:
<input type="text" pattern="(foo|bar)" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());">
Will add the css class "valid" to the input field parent, if the value is foo or bar.
.valid {
border: 1px solid green;
}
.valid::after {
content: '✅'
}
<form oninput="this.querySelector('#submitButton').disabled = !this.checkValidity();" onsubmit="event.preventDefault(); console.log('Submit prevented but the form seems to be valid.'); return false;">
<fieldset>
<label for="newslettermail">E-Mail</label>
<!-- you could also define a more specific pattern on the email input since email would allow foo#bar as valid mail -->
<input type="email" id="newslettermail" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
</fieldset>
<fieldset>
<input type="checkbox" id="newsletterAcceptTos" oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" required>
<label for="newsletterAcceptTos">I accept the Terms of Service</label>
</fieldset>
<fieldset>
<label for="textFieldWithPattern">Enter <strong>foo</strong> or <strong>bar</strong></label>
<input type="text" id="textFieldWithPattern" pattern="^(foo|bar)$" required oninput="this.parentNode.classList.toggle('valid', this.checkValidity());" >
</fieldset>
<button type="submit" id="submitButton" disabled>Submit</button>
<button type="submit">Force submit (will show errors on invalid input)</button>
</form>
I've got two text boxes for first and last name. I also have a button to save the data. The button has an event handler where it grabs the data from the fields and posts them with an ajax call to my API, using jquery.
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Here is an example which may help you:
$('#save').click(function() {
var errors = [];
var name = $('#name').val();
var vorname = $('#vorname').val();
if (!name) {
errors.push("Name can't be left blank");
}
if (!vorname) {
errors.push("Vorname can't be left blank");
}
if (errors.length == 0) {
console.log('Ajax started');
//put here your ajax function
} else {
for (var i in errors) {
console.log(errors[i]);
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Name" id="name"><br>
<input placeholder="Vorname" id="vorname"><br>
<button id="save">Save</button>
here is an example using the popular add on jquery validate. https://jqueryvalidation.org/
click the run snippet button below
$(document).ready(function() {
$("#form").validate({
rules: {
"firstname": {
required: true,
},
"lastname": {
required: true,
}
},
messages: {
"firstname": {
required: "Please, enter a first name"
},
"lastname": {
required: "Please, enter a last name"
},
},
submitHandler: function(form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<button type="submit">Submit</button>
</form>
Without seeing your code, it is very difficult to guess the correct scenario to provide examples for.
Given the following HTML:
<form>
<input type="text" class="text1">
<input type="text" class="text2">
<button type="button">Send</button>
</form>
You could use this for the jQuery part:
$('button').click(function() {
var txt1 = $(this).siblings('.text1').val();
var txt2 = $(this).siblings('.text2').val();
if (txt1.length && txt2.length) {
// do your ajaxy stuff here
} else {
alert("Imput some friggin' text!");
}
});
$(this) selects the button clicked.
.siblings('.text1') selects the input with class text1 inside the same block as the clicked button.
https://jsfiddle.net/sg1x0c3q/7/
As per my comments I would recommend using a form. But if you want a pure JS solution here you go. (if you want a form based solution just ask)
// convert all textareas into key value pairs (You can change the selector to be specific to your markup)
const createPayload = () => {
return [].slice.call(document.querySelectorAll('textarea')).reduce((collection, textarea) => ({
...collection,
[textarea.name]: textarea.value
}), {})
}
// Compare Object values against values that are not falsy (you could update the filter with a RegExp if you wanted more complicated validation)
const objectHasAllValues = obj => {
return Object.values(obj).length == Object.values(obj).filter(value => value).length
}
// If all key value pairs are not falsy then submit
window.submit = () => {
const payload = createPayload()
if (objectHasAllValues(payload)) {
fetch('/your/api', payload)
}
}
This solution presumes that your API expects a JSON payload. If you are expecting to send form data then you would need to use the formData js api.
This scales and doesn't need jQuery :)
Working example here https://jsfiddle.net/stwilz/dxg29mkj/28/
I want validation on my two textboxes (so they can't be left blank), but I don't know how to trigger that when my button is pressed. I am not using the <form> tag for this; I'm doing an ajax call when the button is pressed.
Answer to form validation. I assume that First name and Last name can only contain alphabets ,i.e., only a-z and A-Z.
//This function will trim extra whitespaces form input.
function trimInput(element){
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s){
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name){
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#myForm').submit(function(e){
e.preventDefault();
var fname = $(this).find('input[name="fname"]');
var lname = $(this).find('input[name="lname"]');
var flag = true;
trimInput(fname);
trimInput(lname);
if(isEmpty($(fname).val()) === false || isName($(fname).val()) === false){
alert("First name is invalid.");
flag = false;
}
if(isEmpty($(lname).val()) === false || isName($(lname).val()) === false){
alert("Last name is invalid.");
flag = false;
}
if(flag){
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="myform" id="myForm" method="post" action="#">
<input type="text" name="fname" placeholder="Firstname">
<input type="text" name="lname" placeholder="Last Name">
<input type="submit" name="submit" value="Submit">
</form>
I am not using the <form> tag for this.
Then the code will be like
//This function will trim extra whitespaces form input.
function trimInput(element) {
$(element).val($(element).val().replace(/\s+/g, " ").trim());
}
//This function will check if the name is empty
function isEmpty(s) {
var valid = /\S+/.test(s);
return valid;
}
//This function will validate name.
function isName(name) {
var valid = /^[a-zA-Z]*$/.test(name);
return valid;
}
$('#submit').click(function() {
var fname = $('#fname');
var lname = $('#lname');
var flag = true;
trimInput(fname);
trimInput(lname);
if (isEmpty($(fname).val()) === false || isName($(fname).val()) === false) {
alert("First name is invalid.");
flag = false;
}
if (isEmpty($(lname).val()) === false || isName($(lname).val()) === false) {
alert("Last name is invalid.");
flag = false;
}
if (flag) {
alert("Everything is Okay");
//Code to POST form data goes here...
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="fname" name="fname" placeholder="Firstname">
<input type="text" id="lname" name="lname" placeholder="Last Name">
<button type="button" id="submit" name="submit">Submit</button>
Check the code on jsFiddle.
Hope this will be helpful.
I have a form, a simple form:
<form>
<input class="u-full-width" type="text" placeholder="First Name" id="firstNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="text" placeholder="Last Name" id="lastNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="email" placeholder="Email" id="emailInput">
<span class="error" aria-live="polite"></span>
<select class="u-full-width" name="state" id="stateInput">
<option value="selectstate">State</option>
</select>
<span class="error" aria-live="polite"></span>
<input id="submit" class="button-primary submit_button" type="submit" value="Submit">
<span class="success" aria-live="polite"></span>
</form>
Essentially I have a eventHandler wired to the form which is listening for the submit event.
theForm.addEventListener('submit', function(e) {
var x = validate(e);
if (x) {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
console.log('There is now data from the form: :) ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
}
}, false);
The validate function:
function validate(e) {
var formData = {
'firstName': null,
'lastName': null,
'email': null,
'stateInput': null
}
// Error tracking variable
var error = false;
// Do validations
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,}))$/;
if ((firstNameInput.value == '') || (firstNameInput.value == null)) {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if ((lastNameInput.value == '') || (lastNameInput.value == null)) {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value)) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if ((stateInput.value == 'selectstate')) {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
console.log('There is no data from the form: ');
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
}
return false;
} else {
return true;
}
}
I would think the conditional in the handler would work like this:
It would only fire if the x was true; which it would be if there was a true outcome i.e. the form submitted successfully. the obj, would get filled with the dat and then I would console.log the fields via a for in loop
I am having problems understanding why you can't get data from this function?
Any help would be appreciated...
var formData = { is contained within your validate() function but you are trying to access it from within the anonymous form submit function.
To access it in both places, you either need to pass it as an argument or declare it in a higher scope, outside of both functions like this:
var formData = {
firstName: null,
lastName: null,
email: null,
stateInput: null
}
function validate(e){
}
theForm.addEventListener('submit', function(e) {
});
Additionally, right now, your "State" dropdown will always fail validation because you only have one choice and that choice is considered invalid by your validation function.
Your tests for input in the text fields that check for null is not going to help you at all because an input that contains no data will always return '', which you are already testing for, so just that one test is fine, although you may want to change it to test for: input.value.trim() === '' because the trim() function will remove any leading or trailing spaces in the input.
Finally, when all the form data is valid, you will only see the console report for a brief moment, because the form will submit and cause a redirect to the form's action, so the current page will unload and the console will clear itself out.
Here's the whole thing put together:
var formData = {
firstName: null,
lastName: null,
email: null,
stateInput: null
}
var theForm = document.querySelector("form");
var firstNameInput = document.getElementById("firstNameInput");
var lastNameInput = document.getElementById("lastNameInput");
var emailInput = document.getElementById("emailInput");
var stateInput = document.getElementById("stateInput");
theForm.addEventListener('submit', function(e) {
if (validate(e)) {
formData['firstName'] = firstNameInput.value;
formData['lastName'] = lastNameInput.value;
formData['email'] = emailInput.value;
formData['stateInput'] = stateInput.value;
logger('There is now data from the form: :) ');
}
}, false);
function validate(e) {
// Error tracking variable
var error = false;
// Do validations
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,}))$/;
if (firstNameInput.value.trim() === '') {
firstNameInput.classList.add('invalid-input');
firstNameInput.nextElementSibling.style.display = 'block';
firstNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (lastNameInput.value.trim() === '') {
lastNameInput.classList.add('invalid-input');
lastNameInput.nextElementSibling.style.display = 'block';
lastNameInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
if (!emailPattern.test(emailInput.value.trim())) {
emailInput.classList.add('invalid-input');
emailInput.nextElementSibling.style.display = 'block';
emailInput.nextElementSibling.innerHTML = 'Please enter valid email address!';
error = true;
}
if (stateInput.value === 'selectstate') {
stateInput.classList.add('invalid-input');
stateInput.nextElementSibling.style.display = 'block';
stateInput.nextElementSibling.innerHTML = 'Not valid!';
error = true;
}
// If error, stop the event
if (error) {
e.preventDefault();
e.stopPropagation();
logger('There is at least one empty field in the form: ');
return false;
} else {
return true;
}
}
function logger(message){
console.clear();
console.log(message);
for (var prop in formData) {
console.log(prop + ' : ' + formData[prop]);
// This line will fail here in Stack Overflow, but is correct and
// will work in a real browser environment. Uncomment it for your use.
// localStorage.setItem(prop, formData[prop]);
}
}
#spacer { height:100px; }
<form>
<input class="u-full-width" type="text" placeholder="First Name" id="firstNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="text" placeholder="Last Name" id="lastNameInput">
<span class="error" aria-live="polite"></span>
<input class="u-full-width" type="email" placeholder="Email" id="emailInput">
<span class="error" aria-live="polite"></span>
<select class="u-full-width" name="state" id="stateInput">
<option value="selectstate">State</option>
<option value="someSate">Some State</option>
</select>
<span class="error" aria-live="polite"></span>
<input id="submit" class="button-primary submit_button" type="submit" value="Submit">
<span class="success" aria-live="polite"></span>
</form>
<div id='spacer'></div>
I am trying to write a pure JavaScript form validation that will add an error message next to the label elements if the input is empty.
The confirmEmail input gets an additional error message if it does not match the email input
My problem is that if you hit the submit button when all fields are empty, then put a value into the email input but leave confirmEmail empty and hit submit again, both error messages will appear next to the confirmEmail's label. The ideal result would be that confirmEmail only has text that says "Email does not match"
Here is a fiddle: http://jsfiddle.net/R5e2T/
Here is my HTML:
<div id="theForm">
<div>
<label for="firstName">First Name:</label>
<br>
<input type="text" id="firstName" name="first" value="" />
</div>
<div>
<label for="lastName">Last Name:</label>
<br>
<input type="text" id="lastName" name="last" value="" />
</div>
<div>
<label for="email">Email:</label>
<br>
<input type="email" id="email" name="email" value="" />
</div>
<div>
<label for="confirmEmail">Confirm Email:</label>
<br>
<input type="text" id="confirmEmail" name="confirmEmail" value="" />
</div>
<button type="button" id="submitButton">Submit</button>
</div>
Here is my JavaScript:
function validate () {
var theForm = document.getElementById('theForm'),
firstName = document.getElementById('firstName'),
lastName = document.getElementById('lastName'),
email = document.getElementById('email'),
confirmEmail = document.getElementById('confirmEmail'),
label = theForm.getElementsByTagName('label'),
input = theForm.getElementsByTagName('input'),
inputLength = input.length;
// Remove any spans that may have been added by the next for loop
for (var x = 0; x < inputLength; x++) {
var currLbl = label[x];
if ( currLbl.parentNode.getElementsByTagName('span').length > 0 ) {
var span = currLbl.parentNode.getElementsByTagName('span')[0];
removeElement(span);
}
}
// Error checking for the form.
// Add error message next to any element that has a blank value.
for (var i = 0; i < inputLength; i++) {
// innerText for IE, textContent for other browsers
var labelText = label[i].innerText || label[i].textContent;
var currLabel = label[i];
var text = document.createTextNode( labelText + ' cannot be empty');
if ( input[i].value === '' ) {
currLabel.parentNode.style.color = 'red';
currLabel.insertAdjacentHTML('afterend', ' <span>cannot be empty</span>');
}
else if ( input[i].value !== '') {
currLabel.parentNode.style.color = '';
}
}
// Test to see if confirmEmail is equal to email.
// If not add a warning message next to confirmEmail's label
if (confirmEmail.value !== email.value) {
var labelElement = confirmEmail.parentNode.getElementsByTagName('label')[0]
labelElement.insertAdjacentHTML('afterend', ' <span>Email does not match</span>');
labelElement.parentNode.style.color = 'red';
}
// Test to make sure all inputs have a value,
// and that confirmEmail equals email.
if (firstName.value !== '' && lastName.value !== '' && email.value !== '' && confirmEmail.value !== '' && email.value === confirmEmail.value) {
alert("Submitted!!!");
return true;
} else {
return false;
}
};
// Remove Element function
function removeElement(node) {
node.parentNode.removeChild(node);
}
(function () {
var button = document.getElementById('submitButton');
button.addEventListener('click', validate, false);
}());
I forked your fiddle.
What I did was to use innerHtml and just replace the text of the label, instead of creating new span-nodes and appending them to the document.
I store the original label, like "E-Mail" in a dataset variable, so that I can reset the label later.
Another solution is to add this before you add the "Email doensn't match" message:
var oldSpan = labelElement.parentNode.getElementsByTagName('span')[0];
removeElement(oldSpan);
An even better solution would be to check for confirmEmail matching email before checking for empty fields and do not add the "cannot be empty" message if another error message has been added already.