O'Reilly logo

JavaScript & DHTML Cookbook by Danny Goodman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Performing Common Text Field Validations

NN 2, IE 3

Problem

You want to verify that a text box contains one of the following: any text, a number, a string of a fixed length, or an email address.

Solution

Apply the library of text field validation routines shown in the Discussion (Example 8-1 and Example 8-2) to your form. The library includes the following functions:

isNotEmpty( )

The field has one or more characters in it.

isNumber( )

The value is a number.

isLen16( )

The field contains exactly 16 characters.

isEMailAddr( )

The field contains a likely email address.

For real-time validation of text box entries, use an onchange event handler in the input element and pass a reference to the element by way of the this keyword. For example, the following input element could be used for an email address:

<input type="text" size="30" name="eMail" id="eMail" 
    onchange="isEMailAddr(this)" />

See Recipe 8.3 for an example of how these validation functions can be linked together in batch validation prior to submitting the form. The return values from the validation functions are vital for successful operation triggered by the form's onsubmit event handler.

Discussion

Example 8-1 shows a set of fully backward-compatible text validation functions. All of these functions are to be invoked by both the onchange event handler of the text box and a batch validation function triggered by the onsubmit event handler of the enclosing form. All functions are passed references to the form control invoking ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required