Based on user statistics, users prefer to have the form validated as they type so they do not have to come back and correct stuff after they submitted the whole form. In our example I will show you how to validate the form with multiple email addresses. You can start by defining CSS class called “incorrect_email” where you define how the input field should look like when the validation fails. I can imagine you will define something like this.
.incorrect_email {
border: 1px solid red;
background: pink;
color: red;
}
After this we will create jQuery script which will validates every input field which has assigned class “email_validation”. This could be done in so many ways but I have chosen this for its simplicity. The key here is to user blur() function to validate the input field right after the user leaves the field and it does not matter if its by pressing TAB or clicking with mouse.
$('form input').blur(
// check the input fields which has a class email_validation as we expect more email fields in the form
if($(this).hasClass('email_validation')){
// get the current value
var email = $(this).val();
// define regular expression for email
var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// validate the email address
if(!filter.test(email)){
// email incorrect add the class "incorrect_email"
$(this).addClass("incorrect_email")
// email corrected remove the class "incorrect_email"
}else if(filter.test(email)){
// you could also check in this point if the the input has already the class...
$(this).removeClass("incorrect_email");
}
}
);
This can be quite handy if you have forms with multiple fields and few of them are email type (for example: inviting your contacts). You might also need to do some other type of validations like if the fields are empty and so on, this is just a part of your validation function.