I wrote my custom jquery validation script to validate the fields in the form (all of which are required but the way the code is structured is that the fields are validated one by one and not all at once (when the submit button is clicked) .The code is given below
$('#contactForm').submit(function () {
$(".error").remove();
var name = $("#name").val();
var email = $('#email').val();
var subject= $('#subject').val();
var message = $('#message').val();
var hasError = false;
var emailReg = /^[+a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
if(name == '') {
$("#name").after('<span class="error">This field is required.</span>');
hasError = true;
}
else if(subject == '') {
$("#subject").after('<span class="error">This field is required.</span>');
hasError = true;
}
else if(message == '') {
$("#message").after('<span class="error">This field is required.</span>');
hasError = true;
}
else if(!emailReg.test(email)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
else if(email == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
How do I modify this code so that all the fields get validated at the same time.
I did try using the jquery validate function but for some reason,when I used that ,it would clash with other jquery elements with my page resulting in the form getting submitted despite having incorrct values
Change all
else iftoif's.