I'm trying to validate a contact form using jQuery. The name field validates correctly using this function, but no matter what I do I get the error message in the email input whenever I try to send, even with a valid email. At this point I'm truly lost and would really appreciate the help. I'm pretty sure the problem is in the regex in the email if statement (!/^S+@S+.S+$/.test(email.val())), but I just can't figure it out. Here is the function I am using
$(function(){
var required = ["name", "email", "message"];
emptyerror = "Please fill out this field";
emailerror = "Please enter a valid e-mail";
email = $("#email");
errornotice = $("#error");
$("#contactForm").submit(function() {
for (var i = 0; i < required.length; i++) {
var inputField = $('#'+required[i]);
if ((inputField.val() == "") || (inputField.val() == emptyerror)) {
inputField.addClass("needsfilled");
inputField.val(emptyerror);
errornotice.fadeIn(750);
}
else {
inputField.removeClass("needsfilled");
}
if (!/^S+@S+.S+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
if ($(":input").hasClass("needsfilled")) {
return false;
}
else {
errornotice.hide();
return true;
}
}
});
$(":input").focus(function() {
if ($(this).hasClass("needsfilled")) {
$(this).val("");
$(this).removeClass("needsfilled");
}
})
});
On a side note, I know that there are way better ways to validate not using jQuery/js. But this is for a school project that requires it to be done with javascript, even if it has to be overly simplified.
Thank you
Aucun commentaire:
Enregistrer un commentaire