Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- validate yyyy-mm-dd


Dabrowski - 12:52 pm on Sep 16, 2008 (gmt 0)


To properly validate with Javascript, you'd first have to validate the string as Fotiman suggests.

Of course, that's if the used a '-' as a separator! What if they entered yyyy/mm/dd?

I prefer to use this, that way the user can enter either and it'll still work. This will change '/' to '-' first:
myString.replace( /\//, "-");
if( !(myString.match(/^\d{4}-\d{2}-\d{2}$/)) {
// return with error
}

Then you'd have to split the string:
myYMD = myString.split( "-");

An easy way of checking if the date is valid is trying to set the date you're given, then seeing if it's the same. If the date is invalid the Date function will 'wrap' it to the correct day/month. e.g., if you try to set the 40th of Jan, it will wrap to 9th Feb.

So:
// Bear in mind that months start at 0
myYMD[1]--;
myDate = new Date( myYMD[0], myYMD[1], myYMD[2]);
if( myDate.getFullYear() != myYMD[0]
&& myDate.getMonth() != myYMD[1]
&& myDate.getDate() != myYMD[2]) {
// date entered was invalid!
}


Thread source:: http://www.webmasterworld.com/javascript/3744781.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com