Workshop: Validating a Form
Listing 12.3 A form with a validation script
This form uses a function called validate to check the data in each of the form fields. Each if statement in this function checks a field's length. If the field is long enough to be valid, the form can be submitted; otherwise, the submission is stopped and an alert message is displayed.
This form is set up to send its results by email, as in listing 12.2if you wish to use this feature, be sure to read the information about email forms earlier in this hour and change firstname.lastname@example.org to your desired email address.
The <form> tag uses an onSubmit event handler to call the validate function. The return keyword ensures that the value returned by validate will determine whether the form is submitted.
You can also use the onChange event handler in each form field to call a validation routine. This allows the field to be validated before the Submit button is pressed.
Figure 12.2 shows this script in action, as displayed by Netscape. The form has been filled out except for the name, and a dialog box indicates that the name needs to be entered.
Figure 12.2. The form validation example in action.