Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Form Validation Techniques
By Scott Isaacs

One of the best uses of JavaScript is to validate user input. This article contains an excerpt from Scott Isaacs' book, Inside Dynamic HTML (Buy Now), explaining three techniques for validating user input. These techniques only work in Internet Explorer 4.0 and later as they rely on Microsoft's implementation of DHTML (except the state validation script that works cross-browser).

Validating While the User Types

Validation can be performed on each character the user types by tracking keyboard events: keypress, keydown, and keyup. The keypress event is the best event to use for tracking keyboard input because the default action of the keypress event is to process the typed character. Returning a value of false to this event prevents the character from being processed, so the character won't be appended to the user input. The following example demonstrates how to limit a text box to numeric input.

      <TITLE>Validating While the User Types</TITLE>
      <LABEL FOR="age">Age</LABEL>
         ONKEYPRESS="if ((event.keyCode < 48) ||
            (event.keyCode > 57)) event.returnValue = false;">

This text box allows only ASCII values from 48 to 57, which represents the numerals 0 through 9 on the keyboard. Any other character typed by the user is ignored.

Validating When the User Exits the Control

Immediate validation is most useful for filtering user input. A more common approach is to validate the input at the time the user completes entering a new value. When an invalid value is entered, the user should be notified using at least one of the following two techniques:

  • Modifying the appearance of an element to reflect invalid values
  • Asking the user to correct an invalid value when he or she exits the field

Both techniques take advantage of the onchange event, which is fired at the time the user exits an input control after changing the value. The onchange event is fired on the element immediately prior to the onblur event. It can be used to validate the user's entry and then to display a dialog box or change the form's appearance based on the entry. Canceling the onchange event prevents the user from exiting the control when navigating within the page. If the user is navigating to a new page, canceling this event does not stop the navigation.

The following code demonstrates changing the style of an element based on the entered value. This technique is described in detail in Chapter 11, "Dynamic Styles." Dynamically changing the style is useful for providing the user with clear feedback.

      <TITLE>Validating When Exiting a Control--Technique 1</TITLE>
      <STYLE TYPE="text/css">
         .badValue {background:red; color:white}
      <SCRIPT LANGUAGE="JavaScript">
         function validateNumber() {
            // Get the source element.
            var el = event.srcElement;
            // Valid numbers
            var num = "0123456789";
            event.returnValue = true;
            /* Loop over contents. If any character is not a number,
               set the return value to false. */
            for (var intLoop = 0; 
               intLoop < el.value.length; intLoop++)
               if (-1 == num.indexOf(el.value.charAt(intLoop))) 
            if (!event.returnValue)       // Bad value
               el.className = "badValue"; // Change class.
               // Clear class to use default rendering.
      <LABEL FOR="Age">Age:</LABEL>
      <INPUT ID="Age" TYPE=TEXT SIZE=3 TITLE="Enter your age"

Instead of changing the style of the element, you can warn the user with an Alert dialog box when an invalid value is entered. The following code demonstrates how to alert the user if he or she enters an invalid value in a State field. In addition, this code performs rudimentary formatting by making the user's input uppercase.

      <TITLE>Validating When Exiting a Control--Technique 2</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function checkState(check) {
            // Include the following to test for Canadian provinces.
            /* Canadian provinces included only if
               a second parameter is supplied and is set to true. */
            if (arguments[1])
               states += "ABBCMBNBNFNSONPEPQSK";
            /* If the string is found in an even position, the state
               is valid. */
            return (0 == (states.indexOf(check) % 2));
      <LABEL FOR="state">State:</LABEL>
         ONCHANGE="this.value = this.value.toUpperCase();
            if (!checkState(this.value)){
               alert(`Invalid State');
            return false;}">

Validating When the User Submits the Form

You can use submit-time validation to determine whether related information is valid or to ensure that all required information is supplied. For example, if the user indicates that he or she is married, the spouse's name or other information might also be required. The following code demonstrates how to extend the intrinsic text box control with a required attribute to ensure that it is filled in by the user:

      <TITLE>Validating When the User Submits the Form</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function isEmpty(str) {
            // Check whether string is empty.
            for (var intLoop = 0; intLoop < str.length; intLoop++)
               if (" " != str.charAt(intLoop))
                  return false;
            return true;

         function checkRequired(f) {
            var strError = "";
            for (var intLoop = 0; intLoop<f.elements.length; intLoop++)
               if (null!=f.elements[intLoop].getAttribute("required")) 
                  if (isEmpty(f.elements[intLoop].value))
                     strError += "  " + f.elements[intLoop].name + "\n";
            if ("" != strError) {
               alert("Required data is missing:\n" + strError);
               return false;
      <FORM NAME="demo" ONSUBMIT="return checkRequired(this);">
         User Name: 
            <INPUT TYPE=TEXT NAME="User Name" required><BR>
         E-Mail Address:
            <INPUT TYPE=TEXT NAME="E-Mail Address" required><BR>
         Age (optional): 
            <INPUT TYPE=TEXT NAME="Age"><BR>
         <INPUT TYPE=SUBMIT VALUE="Submit">
User Name:
E-Mail Address:
Age (optional):

This article is from Chapter 10 of the book, Inside Dynamic HTML, Forms and Intrinsic Controls. Inside Dynamic HTML is the ultimate guide to learning and understanding Dynamic HTML in Internet Explorer 4.0 or later. You can order a copy of Inside Dynamic HTML from or your favorite bookstore.

Discuss and Rate this Article