I was searching the web for JavaScript date validation code. All I found were lots of really bad ideas. Some were quite complicated. John Gang was on the right track. I didn’t see Chris Hogben’s article initially, but he used the right algorithm.
Still, nobody offered the complete solution. Given a date string YYYY-MM-DD, is the date valid?
The smart way to do this is to (a) parse the date string with a regular expression, (b) construct a date object and (c) compare what you got out of the date object to what you put in. To make this really convenient, we’ll use JavaScript’s proptotype functionality to extend the String class, making this available to any string:
var IsoDateRe = new RegExp("^([0-9]{4})-([0-9]{2})-([0-9]{2})$");
var matches = IsoDateRe.exec(this);
if (!matches) return false;
var composedDate = new Date(matches[1], (matches[2] – 1), matches[3]);
return ((composedDate.getMonth() == (matches[2] – 1)) &&
(composedDate.getDate() == matches[3]) &&
(composedDate.getFullYear() == matches[1]));
}
Here’s the method in action:
alert(a + (a.isValidDate() ? " is a valid date" : " is not a valid date"));