Form Validation

Make Sure Your Forms are Filled In

Once you have an HTML form up and running, you will often want to make sure that all the important fields are filled in. For example, if you are going to send an email confirmation letter, the email address should be included in the form fields, and it should be an email address that works.

There are two ways to validate your forms:

  1. Using JavaScript
  2. Using a CGI script

Pros and Cons of Using JavaScript for Validating Forms

Pros

  • Using JavaScript you don't use any server processor time. All the processing is done on the client computer.
  • It often appears to work faster than the CGI validation.
  • Since the form page has not changed, it is easy for the reader to fix the errors.

Cons

  • JavaScript only works on browsers that have it enabled. If the JavaScript is disabled, your error checking doesn't get done.

Pros and Cons of Using CGI for Validating Forms

Pros

  • Using a CGI to validate ensures that every time the form is submitted, the validation will run.

Cons

  • CGI puts more load on the Web server, and every function that is included in the CGI is one more task for the server.
  • CGI can be slow to run.
  • If there is an error, the customer has to either go back to the first page of the form, or the CGI needs another function to rewrite the form page.

The way I handle this is to have the majority of the error checking done with JavaScript. That way, it is fast and easy for the readers.

I then recheck the vital elements of the form with the CGI.

Page 2: How to Use JavaScript to Validate HTML Forms

This article is part of the HTML Forms Tutorial

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";
    }
  1. 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";
    }
  2. 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

    1. This portion of the script shows how to validate for an email address. It is a very simple validation, it only checks to make sure that there is a @-sign and a period. People can still put in fake email addresses, but this helps reduce the wrong entries a little.
      if (theForm.email.value == "")
      {
        error += "You must include an accurate email address for a response.\n";
      }
      if ((theForm.email.value.indexOf ('@',0) == -1 ||
      theForm.email.value.indexOf ('.',0) == -1) && theForm.email.value != "")
      {
        error += "Please verify that your email address is valid.";
      }
    1. This is the meat of the script. It does two things, first it checks to see if there is an error set. If there is, it displays it as an alert message. Then it sends the return value of false, so that the form information is not sent to the server. Your error messages (set in the above if statements), all include a "\n" at the end of the line. This tells the browser to insert a carriage return (or "enter" or "new line") at the end of the line. Then, if there are several error messages they will all be on separate lines. If there are no error messages set, then the error variable will be blank (from where we set it at the top of the script), and so the form information will be sent to the server to be acted upon by the CGI.
      if (error != "")
      {
        alert(error);
        return (false);
      } else {
        return (true);
      }
    2. Don't forget to close your script.
      }
      // -->
      </script>

    Then, to call the script, put an onsubmit element in the form tag:

    <form action="" method="post" onsubmit="return Validator(this);">

    See the validation script in action.

    Page 4: Use a Perl CGI script to validate your HTML forms.

    This article is part of the HTML Forms Tutorial

    CGI for Validating Forms

    This Perl script CGI snippet does the same thing as the JavaScript. It checks to see if the required fields are there, and if not, saves an error message into a variable for display:

    #!/usr/local/bin/perl

    $error = "";
    if ($in{'dd'} eq "")
    {
      $error += "<p>Please select from the drop down box.</p>";
    }
    if ($in{'words'} eq "")
    {
      $error += "<p>Please include some words in the text box.</p>";
    }
    # ... continue validating all fields

    if ($error)
    {
      print "Content-type: text/html \n\n";
      print "<html><head><title>Error</title>";
      print "</head><body&gt";
      print "<h2>An Error Has Occurred</h2>";
      print $error ;
      print "Please go back and correct these errors.";
      print "</body></html>";
    } else {
      # Go on with the CGI ...
    }

    The difference with how the CGI writes the error message is that instead of a "\n", it uses the HTML paragraph tag to put a new line in between each error.

    And Now You've Validated Your Form

    With the two methods, CGI and JavaScript, you've validated an HTML form so that more of the parts that are sent to you are accurate.

    This article is part of the HTML Forms Tutorial