How can I combine these two functions so that they both work? Right now, I can only get one to validate and not the other.
SAMPLE OF THE JAVASCRIPT:
function validateForm() {
var x=document.forms["giftCert"]["gift_name"].value;
if (x==null || x=="") {
errMsg = "The recpient's name is required.";
$("div#emptyName").show();
$("div#emptyName").html(errMsg);
return false;
}
}
function validateForm() {
var x=document.forms["giftCert"]["gift_email"].value;
if (x==null || x=="") {
errMsg2 = "The recpient's email address is required.";
$("div#emptyEmail").show();
$("div#emptyEmail").html(errMsg2);
return false;
}
}
SHORT VERSION OF THE FORM HTML:
<form action="http://ww6.aitsafe.com/cf/voucher.cfm" method="post" name="giftCert" onsubmit="return validateForm()" />
*Name:<input type="text" name="gift_name">
<div id="emptyName" class="error"></div>
*Email: <input type="text" name="gift_email">
<div id="emptyEmail" class="error"></div>
<input class="button" type="submit" value="Add to Cart" />
</form>
You can put the code in the same function.
Since much of the code is nearly identical, you can put the
"Name"and"Email"values in an Array, and loop the Array, invoking the identical code, dropping in the appropriate value where needed.This uses the
Array.prototype.everyto indicate if each value in the Array passed validation.If either item fails validation, it returns
undefined, the loop halts andvalidateFormreturnsfalse.Every item that passes validation returns
true. If all items pass validation,.everywill returntrue, and the form proceeds.If you want to make sure all the validations run, you can use
.filter(), and returntrueon a failure, so that it will add an item to the resulting Array. If there were no failures, the Array will be empty.Then test the
.lengthof the Array, and return a comparison to0.