Validating a date in javascript

Each of these values is then tested against an allowed range (days: 1 - 31; months: 1 - 12; years: 1902 - 2017; and so on).

This script only confirms that the input format is correct and that each individual value falls within its allowed range.

We have also checked the leap year factor for the month of February.

In this case, we've created a stand-alone functions which will validate a date field: In each case the value passed to the function is the form field rather than the field value.

For example, when the date is checked, the return value, , is an array with elements 1 through 3 containing the day, month and year components of the input string.

For the time check, the array returned includes the hour (pos 1), minutes (pos 2) and, optionally, the am/pm string (pos 3).

The output will be almost identical to the earlier examples.

In this simple example we can even rewrite the In practice most modern browsers will now use HTML form validation to preempt any Java Script validation - with the notable exception of Safari. Visitors from some countries may find it confusing that we're using the and vice-versa as the year and day values have now changed position.

Leave a Reply