Home > Articles > Open Source > Ajax & JavaScript

  • Print
  • + Share This
This chapter is from the book

Workshop: Validating a Form

JavaScript's single most useful purpose is probably validating forms. This means using a script to verify that the information entered is valid—for example, that no fields are blank and that the data is in the right format.

You can use JavaScript to validate a form whether it's submitted by email or to a CGI script, or is simply used by a script. Listing 12.3 is a version of the name and address form that includes validation.

Listing 12.3 A form with a validation script

<html>
<head>
<title>Form Example</title>
<script LANGUAGE="JavaScript" type="text/javascript">
function validate() {
   if (document.form1.yourname.value.length < 1) {
     alert("Please enter your full name.");
     return false;
   }
  if (document.form1.address.value.length < 3) {
    alert("Please enter your address.");
    return false;
  }
  if (document.form1.phone.value.length < 3) {
    alert("Please enter your phone number.");
    return false;
  }
  return true;
}
</script>
</head>
<body>
<h1>Form Example</h1>
<p>Enter the following information. When you press the Submit button,
the data you entered will be validated, then sent by email.</p>
<form name="form1" action="mailto:user@host.com" enctype="text/plain"
 method="POST" onSubmit="return validate();">
<p><b>Name:</b> <input TYPE="TEXT" SIZE="20" NAME="yourname">
</p>
<p><b>Address:</b> <input TYPE="TEXT" SIZE="30" NAME="address">
</p>
<p><b>Phone: </b> <input TYPE="TEXT" SIZE="15" NAME="phone">
</p>
<p><input TYPE="SUBMIT" VALUE="Submit"></p>
</form>
</body>
</html>

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.2—if you wish to use this feature, be sure to read the information about email forms earlier in this hour and change user@host.com 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.

TIP

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.

  • + Share This
  • 🔖 Save To Your Account