JavaScript date validation
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"));
March 9th, 2007 at 4:53 am
Thank you, this is a very good script, just what I was looking for. I will reference you in my code.
November 30th, 2007 at 8:30 am
Absolute lifesaver. Just made a quick change for UK date format and all is good. Thanks
January 13th, 2008 at 1:45 am
Thanks! exactly what i needed :)
April 17th, 2008 at 9:33 am
thanks a lot.
that’s exactly what i am looking for.
May 8th, 2008 at 11:11 pm
Thank you very much.This was what i needed for my project.
August 11th, 2008 at 10:54 am
This is the simpliest date validation method I found after searching the web. Thanks…
September 20th, 2008 at 10:51 am
[...] was searching the web for JavaScript HTML entity unescaping code. I found lots of really bad ideas. Sound familiar? Some were quite [...]
October 19th, 2008 at 4:39 am
how to make format dd-mm-yyyy
thanks