How many times have you found yourself writing JavaScript validation functions that look like this:
function validateFields(){Look OK to you? Well I suppose it is really. After all, it does the job. However, if a pure-coder saw it they would probably moan that is not very modular. meaning that the same logic is repeated over and over. Not only that. If you wanted to add another field to the list then you have to use the same routine again. What if you want to change the wording on the alert message - you have to make the change four times!
var frm = document.forms[0];
if (frm.FirstName.value == ""){
alert("You need to enter a First Name");
frm.FirstName.focus();
return false;
}
if (frm.LastName.value == ""){
alert("You need to enter a Last Name");
frm.LastName.focus();
return false;
}
if (frm.Email.value == ""){
alert("You need to enter an Email Address");
frm.Email.focus();
return false;
}
if (frm.Phone.value == ""){
alert("You need to enter a Phone Number");
frm.Phone.focus();
return false;
}
}
function validateField(fld, msg){What we've done here is remove all the common code from each routine and place it in one single place in the "validateField" function. We then call this one function four times. There is still more code than needs be though. Let's use an array to make it more powerful/simple.
if ( fld.value == "" ){
alert( msg );
fld.focus();
return false;
}
return true;
}
function validateFields(){
var frm = document.forms[0];
if (!validateField(frm.FirstName,"You need to enter a
First Name"))
return false;
if (!validateField(frm.LastName,"You need to enter a
Last Name"))
return false;
if (!validateField(frm.Email,"You need to enter an
Email Address"))
return false;
if (!validateField(frm.Phone,"You need to enter a
Phone Number"))
return false;
return true
}
function validateFieldArray( flds ){The function now builds an array where the first element of each entry is the field object that is required and the second is the message string. This array is then passed in to the "validateFieldArray" function. This loops through each element of the array and validates the fields one by one.
for (var i = 0; i < flds.length; i ++){
if ( flds[i][0].value == "" ){
alert( "You need to enter " + flds[i][1] );
flds[i][0].focus();
return false;
}
}
return true;
}
function validateFields(){
var frm = document.forms[0];
var flds = new Array();
flds[flds.length] = [frm.FirstName, "a First Name"];
flds[flds.length] = [frm.LastName, "a Last Name"];
flds[flds.length] = [frm.Email, "an Email Address"];
flds[flds.length] = [frm.Phone, "a Phone Number"];
return validateFieldArray( flds );
}
Copyright © 2000 - 2024 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net