This validation works just as the onsubmit validation for an individual field. However, the validation test is wrapped in a for loop that moves through all fields in the form.
Since the function can check every field, we are passing the entire form object, not just a field, to the function.
<script language="JavaScript"> <!-- function validateForm(form) { for (var i = 0; i < form.elements.length; ++i) { if (form.elements[i].value.length == 0) { alert("Entry field " + form.elements[i].name + " is required."); form.elements[i].focus(); return false; } } return true; } //--> </script>
But what if we don't want to check all fields? In such cases, you can add conditional statements to the function. In the example below, the second field is not validated. This is done in the function by incrementing the loop counter, i, when it has the value 1. The function then checks form.elements[i+1], which is the third field in this case, thus skipping the second.
<script language="JavaScript"> <!-- function validateForm(form) { for (var i = 0; i < form.elements.length; ++i) { // if the loop counter is equal to 1 // increment by one: // form.elements[1] becomes form.elements[2] if (i == 1) { ++i; } if (form.elements[i].value.length == 0) { alert("Entry field " + form.elements[i].name + " is required."); form.elements[i].focus(); return false; } } return true; } //--> </script>