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

Validating a Date

NN 4, IE 4

Problem

You want to validate a date entered by the user in a form.

Solution

Use the checkDate( ) function shown in the Discussion. This function takes a text input element as its sole argument and expects the user to enter a date value in either mm / dd / yyyy or mm - dd - yyyy format. For example, the following validation function could be triggered from an onchange event handler of a date entry form field:

function validateDate(fld) {
    if (!checkDate(fld)) {
        // focus if validation fails
        fld.focus( );
        fld.select( );
    }
}

Discussion

Before you undertake validating a date entry, you must clearly understand your assumptions about the users, the purpose of the entry, and what you want to report back to the user for invalid entries. It's comparatively easy to test whether a field expecting a date in the mm / dd / yyyy format has numbers in the right places, but that typically is not good enough. After all, you don't want someone to get away with entering the 45th of June into a date field.

The checkDate( ) validation function in Example 2-3 assumes that users will enter dates in either mm / dd / yyyy or mm - dd - yyyy formats (in that order only), and that the validation must test for the entry of a true date. There is no boundary checking here, so practically any year is accepted. As a form-validation function, this one takes a reference to the text input element as the sole argument (just like the other validation routines in Recipe 8.2). Upon successful validation, ...

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