I have a function (validate) which validates for correct email format on the front end first (to avoid most junk). At the moment it validates a single field and works fine. I tried modifying it to validate any field with class of "email" since there are several email fields on the same page. The second function (validateAny) works partially, it validates and shows the error message but does not add/remove the error class to the elements like it does in the first (validate) function. What am I missing here? Also, I'd like it not to validate the field if it is empty, then I'd like the check to be on the submit button instead. Check jsfiddle
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\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 re.test(email);
}
function validate(){
//$("#wrong-email-mess-create-process").text("");
var email = $("#new-usr-name").val();
if (validateEmail(email)) {
$("#new-usr-name").removeClass('error');
$("#new-usr-name").prev().removeClass('error');
$(".error-mess").fadeOut('fast');
//$("#wrong-email-mess-create-process").text(email + " is valid :)");
} else {
$("#new-usr-name").addClass('error');
$("#new-usr-name").prev().addClass('error');
$(".error-mess").fadeIn('fast');
//$("#wrong-email-mess-create-process").text(email + " is not valid :(");
}
return false;
}
$("#new-usr-name").bind("blur", validate);
function validateAny(efield){
var email = $(efield).val();
if (validateEmail(email)) {
$(efield).removeClass('error');
$(efield).prev().removeClass('error');
$(".error-mess").fadeOut('fast');
} else {
$(efield).addClass('error');
$(efield).prev().addClass('error');
$(".error-mess").fadeIn('fast');
}
return false;
}
$('.email').blur(function(){
if( this.value ) {
validateAny(this.id);
}
});