Wednesday, April 29, 2009

Preventing Non-Existent Dates with JavaScript

When I say "non-existent dates", I mean dates like "April 31" or "June 31," an end-of-the-month date a user might enter if they don't take a moment to review the old "Thirty days hath September" mnemonic rhyme. All decent date pickers/selectors prevents users from entering letters or other inappropriate characters, but few of them bother to check if the date value itself is valid.

You could write a date validation script that took the month and day value submitted by the user and checked it against a list of the maximum number of days for each month, but then your code would also have to determine if the year selected by the user was a leap year in case the user entered "February 29" as their date of choice.

There's a more straightforward way to check the validity of the submitted date: create a JavaScript Date object using the year, month, and day submitted by the user, then extract the year, month, and day values from the newly created Date object and compare those integer values against the ones submitted by the user:

This works because JavaScript's date creation function will accept the integer values for a non-existent date like April 31, 2009 (4, 31, and 2009), but it will quietly translate it into it's real-life equivalent, in this case May 1, 2009. So the integer values pulled from the date object via the getFullYear(), getMonth(), and getDate() functions will not match the integers originally passed into the date creation function, and you know there's a problem.