This is a simple email form validation, with javascript. I first coded the basic 'have you filled in the field" stuff and that worked great, the error message poped up and the form would not submit until corrected.
I then put together a email validation function using reg ex, and things went slightly awry. The reg ex works, so that is cool, but after catching an invalid email address, it submits the form anyway.
Following the logic, you can see that the form gets validate, then the email address is validated, then the form validation function returns true, which is probably why it is submitting with the bad email address.
I never seen an example of this, but can you put a called function into an if statement? So it would go: validate the form, then if the email validation function returns true, go ahead and submit.
Anyway, here is the code:
JS code:
function validateForm ()
{
if (document.contactForm.name.value == "")
{
window.alert ("Please enter your name.");
return false;
}
else if (document.contactForm.email.value == "")
{
window.alert ("Please enter your email address.");
return false;
}
else if (document.contactForm.phone.value == "")
{
window.alert ("Please enter a phone number.");
return false;
}
else if (document.contactForm.message.value == "")
{
window.alert("Please enter a message.");
return false;
}
validateEmail();
return true;
}
function validateEmail()
{
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/ ;
var email = document.contactForm.email.value;
if (emailPattern.test(email) == false)
{
window.alert("Please check your email address.");
return false;
}
}
And the onsubmit call in the form:
<form action="handle_form.php" method="post" name="contactForm" onsubmit ="return validateForm();">
Let me know your suggestions/ideas. Thank you.

New Topic/Question
Reply


MultiQuote



|