Form Validation
  << Back | Home | Next >>


One of the most common and easy uses for JavaScript is form validation. Adding form validation is as simple as including an "onsubmit" event in the FORM tag, and having that call a function which validates the form fields before they are submitted. This saves the trouble of programming error-checking features into your CGI where the form is posted.

Below is an example of a simple form with a JavaScript form validation function. The script verifies that text has been entered into the form box. The form mails the webmaster the text entered by the user. You may copy this code to add a working form to your site, but it is not advisable to use a "mailto:" in the ACTION if you have access to CGI script, as the "mailto:" in the ACTION makes use of the browser's mail client and is a security issue.

Part 1. This is the validate function you need to use, follow the comments

<! - - BEGIN FORM - ->


function validateForm(form) { //This is the name of the function

if (form.FIELD1.value == "") { //This checks to make sure the field is not empty
   alert("This field is empty."); //Informs user of empty field
   form.FIELD1.focus( ); //This focuses the cursor on the empty field
   return false; //This prevents the form from being submitted
// you may copy the above 5 lines for each form field you wish to validate
// Replace the text "FIELD1" with the name you wish to call the field

Part 1. This is the actual form sample, onSubmit="return validateForm(this)" is the line you need.

<!- - Below you'll find the HTML that is the form itself. You may replace the action with either a CGI or your own email address if you do not have access to a CGI script to collect form information. Also, replace the text "FIELD1" with the name you used in the script above.- ->

<FORM METHOD="POST" ACTION="mailto:MAIL@YOURDOMAIN.COM" onSubmit="return validateForm(this)">

<!- - END FORM - ->

Close this window