Validate Forms With JavaScript or CGI

Woman typing on computer with code showing in front of her

nullplus / Getty Images

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.

Two Options for Validation

There are two ways to validate your forms:

  1. Using JavaScript
  2. Using a CGI script.

Pros of Using JavaScript for Validating Forms

  • 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 of Using JavaScript for Validating Forms

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

Pros of Using CGI for Validating Forms

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

Cons of Using CGI for Validating Forms 

  • CGI puts more load on the webserver, 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 you should handle this is to have the majority of the error checking done with JavaScript. That way, it is fast and easy for readers. You then recheck the vital elements of the form with the CGI.

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.
    1. function Validator(theForm)
  3. {  var error = "";
    1. 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){
    2. 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).
    1. var digits = "0123456789";
    2. if (theForm.number.value == "")
    3. {
    4. error += "Please fill in a number.\n";
    5. }
    6. for (var i = 0; i < theForm.number.value.length; i++)
    7. {
    8. temp = theForm.number.value.substring(i, i+1)
    9. if (digits.indexOf(temp) == -1 && theForm.number.value != "")
    10. {
    11.  error += "The numerical text must be a number.\n";
    12.  break;
    13. }}

Validate an Email Address With JavaScript

  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.
    1. if ( == "")
    2. {
    3. error += "You must include an accurate email address for a response.\n";
    4. }
    5. if (( ('@',0) == -1 ||
    6. ('.',0) == -1) && != "")
    7. {
    8. error += "Please verify that your email address is valid.";
    9. }
  2. 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.
    1. if (error != "")
    2. {
    3. alert(error);
    4. return (false);
    5. } else {
    6. return (true);
    7. }
  3. Don't forget to close your script.
    1. }
    2. // --></script>

Then, to call the script, put an on a submit element in the form tag:

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

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:

  $error += "
if ($in{'dd'} eq "")
$error = "";
Please select from the drop down box.
if ($in{'words'} eq "")
$error += "
Please include some words in the text box.
# ... 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.