PCHomepage
Programmer
I use this code on several sites but it seems to be resisting my efforts to add it to a new one. When I submit the empty form as a test, all fields except EMail highlight in yellow but for only a second or two, then the form submits. There is no alert and no yellow on the EMail field. It's not a problem with pop-up blockers since, as mentioned, I use it on other sites on this same system and browser. Any ideas?
The form itself is part of a PHP function but again, it's little different than I use elsewhere.
JavaScript:
function validateFormOnSubmit(theForm) {
var reason = "";
reason += validateEmpty(theForm.Name);
reason += validateEmpty(theForm.Message);
reason += validateEmpty(theForm.SecurityCode);
reason += validateEmail(theForm.EMail);
if (reason != "") {
alert("Some fields need correction:\n" + reason);
return false;
}
return true;
}
function validateEmpty(fld) {
var error = "";
if (fld.value.length == 0) {
fld.style.background = 'Yellow';
error = "Required field(s) missing.\n";
} else {
fld.style.background = 'White';
}
return error;
}
function trim(s) {
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(fld) {
var error = "";
var tfld = trim(fld.value); // value of field with whitespace trimmed off
var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (fld.value == "") {
fld.style.background = 'Yellow';
error = "You didn't enter an email address.\n";
} else if (!emailFilter.test(tfld)) { //test email for illegal characters
fld.style.background = 'Yellow';
error = "Please enter a valid email address.\n";
} else if (fld.value.match(illegalChars)) {
fld.style.background = 'Yellow';
error = "The email address contains illegal characters.\n";
} else {
fld.style.background = 'White';
}
return error;
}
The form itself is part of a PHP function but again, it's little different than I use elsewhere.
HTML:
<form method="POST" onsubmit="return validateFormOnSubmit(this)" name="SendMessage" action="/?ID=3">
<fieldset>
<p><label for="Name">Your Name</label>
<input name="Name" type="text" size="25" value="<?=$Name?>" id="Name"></p>
<p><label for="EMail">Your Email</label>
<input name="EMail" type="text" size="25" value="<?=$EMail?>" id="EMail"></p>
<p><label for="Message">Message</label>
<textarea name="Message" rows="5" cols="65" id="Message"><?=$Message?></textarea></p>
<p><label for="SecurityCode">Security Code</label>
<img src="/quickcaptcha/imagebuilder.php" border="1"> <strong>Enter code as shown</strong> <input name="VerifyCode" value=""></p>
<p><input name="Contact" type="submit" value="Send Message"></p>
</fieldset>
</form>