HTML and CSS Reference
In-Depth Information
Improving Form Validation The form validation code in this exercise works, but it
could be better. The biggest problem is that it validates only one field at a time—if two
fields are invalid, they'll get an error message only for the first one that has a problem.
Fortunately, the script can be tweaked to validate all the fields at once. The key is to
accumulate the error messages and display them all simultaneously at the end of the
function before the return statement.
An array will be used to store the error messages and the return statements, and at the
end, if there are elements in the array, the error message will be created and displayed,
and the validation routine will prevent the form from being submitted.
Here's the script:
<script language=”JavaScript”>
function checkform(thisform) {
var errors = [];
var errorMessage = “Please correct the following errors:\n\n”;
if (!thisform.name.value) {
errors.push(“You must enter a name.”);
}
var selected = false;
for (var i = 0; i < thisform.gender.length; i++) {
if (thisform.gender[i].checked) {
selected = true;
}
}
if (!selected) {
errors.push(“You must choose a gender.”);
}
if (errors.length > 0) {
for (var i = 0; i < errors.length; i++) {
errorMessage += errors[i] + “\n”;
}
alert(errorMessage);
return false;
}
else {
return true;
}
}
</script>
 
Search WWH ::




Custom Search