Developer

Learn how to validate a whole form

With JavaScript, you can validate an entire form. Here's how.

By Emily A. Vander Veer

Unlike field-level validation, form-level validation examines a group (or all) of the values on a form together, as a whole, for consistency. Form-level validation is typically performed just prior to submitting a completed HTML form to a CGI program. We do this to make sure the user filled in every mandatory field before submitting the data to the server.

Validating an entire form is actually pretty easy. In our example, we've removed most of the field-level validation that would automatically pop up an instant alert message. Here's an example.

function isANumber(number) {
  answer = 1;
  if (!parseFloat(number)) {
    //the first digit wasn't numeric
    answer = 0;
  } else {
    //the first digit was numeric, so check the rest
    for (var i=0; i<number.length; i++) {
      if ((number.charAt(i) != "0")
        && (!parseFloat(number.charAt(i)))) {
          answer = 0;
          break;
      }
    }
  }
  if (answer == 1) {
    orderPlaced = true;
  }
  return answer;
}

The above code is basically our old number-checking function but without the JavaScript alerts. In this case, we don't automatically send an error message if the user enters something other than a numeral.

Once the user thinks she's finished with the form, she can hit the Submit button. At that point, we check for any fields that have missing or incorrectly formatted data.

function validateForm() {
  var fixThis = "";
  if
(!(isANumber(document.orderForm.numberOrdered.value))) {
    fixThis += "Please enter a numeric value
for the number of brains field.\n";
  }
  if
(!(exists(document.orderForm.typeField.value))) {
    fixThis += "Please enter the type.\n";
  }
  if
(!(exists(document.orderForm.stateField.value))) {
    fixThis += "Please enter the state.\n";
  }
  if
(!(isAPhoneNumber(document.orderForm.phoneNumber.value))) {
    fixThis += "Please enter the phone number
in the following format: (123)456-7890";
  }
  if
(fixThis != "") {
    alert(fixThis);
  } else {
    document.location.href = "thanks.html";
  }
}

This function works its way through all the fields in the form, checking to make sure each one contains a valid value. If it finds a field without valid data, it adds a new warning message to the fixThis variable and continues on. At the end, it either pops up an alert box containing the various warnings, or it delivers a short "Thank You" to the user.

Note: This example checks the code for a part of the form we haven't covered yet—the State box, which computes sales tax based on the U.S state code the user enters.

Emily A. Vander Veer is the author of numerous Internet-related magazine articles and books, including JavaScript for Dummies, JavaScript for Dummies Quick Reference, and JavaBeans for Dummies, all published by IDG Books.

Editor's Picks

Free Newsletters, In your Inbox