SiteExperts.com 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.

<HTML>
   <HEAD>
      <TITLE>Validating While the User Types</TITLE>
   </HEAD>
   <BODY>
      <LABEL FOR="age">Age</LABEL>
      <INPUT ID="age" TYPE=TEXT SIZE=3 MAXLENGTH=3
         ONKEYPRESS="if ((event.keyCode < 48) ||
            (event.keyCode > 57)) event.returnValue = false;">
   </BODY>
</HTML>

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.

<HTML>
   <HEAD>
      <TITLE>Validating When Exiting a Control--Technique 1</TITLE>
      <STYLE TYPE="text/css">
         .badValue {background:red; color:white}
      </STYLE>
      <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))) 
                  event.returnValue=false;
            if (!event.returnValue)       // Bad value
               el.className = "badValue"; // Change class.
            else
               // Clear class to use default rendering.
               el.className="";
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <LABEL FOR="Age">Age:</LABEL>
      <INPUT ID="Age" TYPE=TEXT SIZE=3 TITLE="Enter your age"
         ONCHANGE="validateNumber();">
   </BODY>
</HTML>

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.

<HTML>
   <HEAD>
      <TITLE>Validating When Exiting a Control--Technique 2</TITLE>
      <SCRIPT LANGUAGE="JavaScript">
         function checkState(check) {
            var states = "ALAKAZARCACOCTDEDCFLGAHIIDILINIAKS";
            states += "KYLAMEMDMAMIMSMNMOMTNENMNVNHNJNMNY";
            states += "NCNDOHOKORPARISCSDTNTXUTVTVAWAWVWIWY";
            // 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));
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <LABEL FOR="state">State:</LABEL>
      <INPUT ID="state" TYPE=TEXT SIZE=2 MAXLENGTH=2
         ONCHANGE="this.value = this.value.toUpperCase();
            if (!checkState(this.value)){
               alert(`Invalid State');
            return false;}">
   </BODY>
</HTML>

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:

<HTML>
   <HEAD>
      <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;
            }
         }
      </SCRIPT>
   </HEAD>
   <BODY>
      <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">
      </FORM>
   </BODY>
</HTML>
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 Amazon.com or your favorite bookstore.

Discuss and Rate this Article