Form Validation
  << Back | Home | Next >>

Instructions:

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 - ->


<SCRIPT>

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
}
</SCRIPT>

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)">
<INPUT TYPE="TEXT" NAME="FIELD1" SIZE=10 MAXLENGTH=60 VALUE="">
<INPUT TYPE="SUBMIT" NAME="ACTION" value="SUBMIT">
</FORM>

<!- - END FORM - ->

Close this window