Verifying Form Input with JavaScript

The World Wide Web "grew up" when they added the ability to display forms. In the days before forms, the Web was only mildly interactive, with just hypertext links to take readers from location to location. Forms allow users to truly interact with the Web. For example, readers can specify search queries using a simple one-line text box.

Forms on the Web consist of two parts: the form itself, which is rendered in the browser, and a CGI script or program located on the server. This script processes the user's input. While it's not exactly rocket science, a stumbling block in creating great Web forms is writing the CGI program. In most cases these programs are written in Perl or C, and can be a bother to implement and debug. A primary job of the CGI program is to validate that the reader has provided correct data, and this can requires pages of code.

JavaScript changes that. With JavaScript you can check the data provided by the reader before it's ever sent to the CGI program. In this way the CGI program can be kept to a bare minimum. And, because the data is only sent after it has been validated, the server need not be bothered until the form entry is known to be good. This saves valuable server resources.


A JavaScript Input Validation Example

Here is a rudimentary example of how to use JavaScript for form input validation. Four text boxes are provided; beside each is a button. Enter text into one of the boxes, and click the button beside it. If you have not entered valid data, you are asked to re-enter it.

Validation example with no form submission
Validation example with form submission to test CGI script


Using the submit Method

Not shown in this demonstration is passing the completed form data to a server. Assuming you've entered valid data, when you click the Submit button JavaScript is told to execute the submit method. At this time the data from the form is transmitted to the CGI program running on the server. The command line for the submit method has been commented-out for this demonstration. In actual use, you'll want to un-comment this line, and add the URL for the CGI program or script in the <FORM> definition tag. You'll also want to change the METHOD from GET to POST, as desired.


Viewing the JavaScript Source

To view the JavaScript code source, choose View, Source. You may wish to save this document for future reference. You may do so by choosing File, Save as. Provide a name for the file and choose OK.



Maintained by John Loomis, last updated 15 Feb 2001

Copyright © 1996, Gordon McComb. All Rights Reserved.