1. Technology

JavaScript Form Validation

Use JavaScript to Validate HTML Forms

By

How to Use JavaScript to Validate HTML Forms

The basic premise of creating form validation is to look for the names of form elements that are required, and if they are empty, display an error message.

Most error checking programs check each field one at a time, and display one error at a time. This can make filling out the form tedious, and people might stop in the middle. If you use the following script and Perl source you will know how to validate an entire form at once, displaying a series of error messages that your reader can then go back and fix.

The JavaScript for Validating a Form

In the head portion of your HTML, you should create a script to do the form validation:

  1. Set up the script, and make sure that it's hidden from browsers that can't handle JavaScript.
    <script language="JavaScript">
    <!-- // ignore if non-JS browser
  2. This is the function call that starts the validation. It's good form to set your variables at the top of your script.
    function Validator(theForm)
    {
      var error = "";
  3. If you have drop-down elements in your forms, you should include the first option as an empty field (e.g. <option value="">choose one</option>) You can include any text you would like on the field, as long as the value is blank. Then, when you validate against it, simply look to see if the first option (the blank one) is still set, if it is, write the error message.
    if (theForm.dd.options[0].selected == true)
    {
      error += "Please select from the drop-down list.\n";
    }
  4. Text elements are the easiest to validate. Simply check to see if the value is empty. If it is, set the error message.
    if (theForm.words.value == "")
    {
      error += "Please fill in the text element.\n";
    }
  5. If you want to validate the type of data within a text field, you have to get a bit fancier. This snippet of script looks at a text box to see if it has non-numerical characters in it (the variable "digits" defines what it is looking for).
    var digits = "0123456789";

    if (theForm.number.value == "")
    {
      error += "Please fill in a number.\n";
    }
    for (var i = 0; i < theForm.number.value.length; i++)
    {
      temp = theForm.number.value.substring(i, i+1)

      if (digits.indexOf(temp) == -1 && theForm.number.value != "")
      {
        error += "The numerical text must be a number.\n";
        break;
      }
    }

Page 3: Validate an Email address with JavaScript

This article is part of the HTML Forms Tutorial

©2014 About.com. All rights reserved.