Print this Section

  
  

Validating Forms

As you have seen, form controls such as textboxes, drop-down lists, radio buttons, checkboxes, and buttons can be used to initiate browser processing to apply HTML techniques to a Web page. In these cases, all processing is local to the Web page, encapsulated within browser scripts or event handlers.

As noted, though, form controls also are devices for submitting information from a Web page to a processing program located on the Web server. Although you may not be producing your own server scripts for form processing, you may have occasion to create forms for submission of information to Web pages created by others. For example, you may create a "guest book" form where visitors submit information about themselves or leave comments about your site. There are common, third-party sites to which this information can be submitted and which produce email messages to you summarizing the submitted information.

Submitting Forms

In these cases and others where form information is sent to an external site for processing, the controls to capture information are surrounded by a <form> tag containing action and method attributes. The former gives the URL of the external page that handles the processing, and the latter indicates how the form information is transmitted (normally through the post method). The form also encloses a "submit" button to activate the form submission; an optional "reset" button can be coded to automatically clear all form fields.


<form id="id" action="url" method="post">
  form controls...
  
  <input type="submit" value="label"/>
  <input type="reset" value="label"/>
</form>

Figure 9-35. General format for submitting a form for server processing.

Information submitted for processing to an external site must be in the formats expected by the processing program. Otherwise, errors can result and expected processing is not performed. Therefore, it is often necessary to verify that the information submitted is complete and in the correct format for processing.

These situations require that when the form's "submit" button is clicked the form information is not immediately transmitted to the processing page. Rather, a local script is run to validate the form and, only if all information is correct, is the form submitted.

An Example Form

The following example presents a form to be submitted to an external Web page for server processing. When the "Submit Form" button is clicked, a local script is called to check on the completeness and accuracy of entered information. Only when the form passes this inspection is it submitted. Otherwise, error messages are displayed for correcting any invalid data values.

Name:
Address:
Email:

Figure 9-36. Example form for validation.

Of course, additional tests can be made on the fields; however, the intent here is to present a general format for validating forms without complicating the processing. Code for the above form and its accompanying script are shown below.


<script type="text/javascript">

function validate()
{
  var isValid = true;

  document.getElementById("NameERR").innerHTML = "";
  document.getElementById("AddressERR").innerHTML = "";
  document.getElementById("EmailERR").innerHTML = "";

  // Check for a name
  if (document.getElementById("FullName").value == "") {
    document.getElementById("NameERR").innerHTML = "Missing name";
    isValid = false;
  }
  // Check for an address
  if (document.getElementById("Address").value == "") {
    document.getElementById("AddressERR").innerHTML = "Missing address";
    isValid = false;
  }	
  // Check for a valid email address
  var validEmail = false;
  for (i=0; i<document.getElementById("Email").value.length; i++) {
    if (document.getElementById("Email").value.charAt(i) == "@") {
      validEmail = true;
      break;
    }
  }
  if (validEmail == false) {		
    document.getElementById("EmailERR").innerHTML = "Incorrect email format";
    isValid = false;
  }	
  return isValid;
}

</script>

<form id="myForm" action="external page" method="post" onsubmit="return validate()" >

<table border="1" style="border-collapse:collapse">
<tr>
  <td style="font-weight:bold">Name: </td>
  <td><input type="text" name="FullName" id="FullName"/>
      <span id="NameERR" style="color:red"></span></td>
</tr>
<tr>
  <td style="font-weight:bold">Address: </td>
  <td><input type="text" name="Address" id="Address"/>
      <span id="AddressERR" style="color:red"></span></td>
</tr>
<tr>
  <td style="font-weight:bold">Email: </td>
  <td><input type="text" name="Email" id="Email"/>
      <span id="EmailERR" style="color:red"></span></td>
</tr>
</table>
<br/>
<input type="submit" value="Submit Form"/>
<input type="reset" value="Clear Form"/>
</form>

Listing 9-24. Code for form validation.

Trapping the Submit Event

The form's destination (its action value) is an external Web page containing a server script to process the information submitted with the form. Normally, this page is called immediate when the submit button (<input type="submit">) is clicked. This submission, however, is contingent upon valid data being entered into the three data fields. Therefore, the form's submit event is trapped with an onsubmit event handler to interrupt submission and call the Validate() function to validate the form.


<form id="myForm" action="external page" method="post" onsubmit="return validate()" >

The format of the onsubmit handler indicates that the submission event is either true or false depending on the value returned from the Validate() function. That is, if onsubmit=true then the form is submitted; if onsubmit=false then the form is not submitted. Therefore, the validate() function must return one of these two values.

Returning Validation Results

The Validate() function is designed to return a true or false value depending on whether the form fields pass their validation tests. The function begins with a validation flag being set,


var isValid = true

indicating initially that the form is valid. If a test of a form field is not passed, then this flag is reset to false. At the end of the script this flag indicates whether all fields are valid (isValid remains true) or whether one of the fields caused the variable to be reset to false. The final statement in the script returns this flag value to the form's onsubmit handler,


return isValid

and the form is submitted to the action site, or not.

The above script can be generalized to serve as a model for writing form validation scripts. As shown below, the validation function sets a flag assuming the form is valid. If any field checks indicate invalid data, then the flag is set to false. At the end of the script, the flag is returned to the form's onsubmit handler to control submission of the form.


<script type="text/javascript">
function validate()
{
  var isValid = true;              // initialize flag = true

  if (field is invalid) {
    display error message;
    isValid = false;               // reset flag = false
  }

  if (field is invalid) {
    display error message;
    isValid = false;               // reset flag = false
  }

  ...

  return isValid;                  // return flag
}
</script>

Listing 9-25. General model for form validation.


TOP | NEXT: Chapter 10 - Dynamic Styles