...

View Full Version : JavaScript Date Validation



whammy
02-08-2003, 12:17 PM
Recently while messing with dates, I noticed an odd quirk in javascript with new Date(), i.e. if someone enters an invalid date, such as 2/29/2003, javascript creates the new date as 3/1/2003.

Having a look around, I couldn't find any scripts that took advantage of this for the sake of date validation... probably someone here has done this before, but I'll post it anyway.

The idea is that if javascript creates a new Date() with a different month, then obviously the date entered is not valid. Most of the scripts I saw used some math to divide by leap year, yadda yadda yadda, but with this feature (?) of javascript, it seems unnecessary.

Right now this code only validates mm/dd/yyyy, but it should be easy to modify to support other formats:



function isDate(sDate) {
var re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
if (re.test(sDate)) {
var dArr = sDate.split("/");
var d = new Date(sDate);
return d.getMonth() + 1 == dArr[0] && d.getDate() == dArr[1] && d.getFullYear() == dArr[2];
}
else {
return false;
}
}


Here's a shorter version that works if you pass in the values separately:



function isDate(mm,dd,yyyy) {
var d = new Date(mm + "/" + dd + "/" + yyyy);
return d.getMonth() + 1 == mm && d.getDate() == dd && d.getFullYear() == yyyy;
}


Comments/modifications? :)

ca_redwards
02-08-2003, 06:53 PM
Funny you should mention that! I use this fact to my advantage in my fully-navigable cross-browser pop-up calendar (http://www.angelfire.com/ca/redwards/html__.calendar.html)...

Originally, I developed this calendar because I wanted an intuitive and convenient way for users to enter valid dates. To keep it friendly, I allow the user to select year, month and day in any order, and rebuild its internal date accordingly. From March 29, 2003, if you select February, the calendar shows you the 29th day of February 2003 (namely, March 1st!).

Some might call that a bug, but what else should I assume?


Originally posted by whammy
Recently while messing with dates, I noticed an odd quirk in javascript with new Date(), i.e. if someone enters an invalid date, such as 2/29/2003, javascript creates the new date as 3/1/2003.

Having a look around, I couldn't find any scripts that took advantage of this for the sake of date validation... probably someone here has done this before, but I'll post it anyway.

Alex Vincent
02-08-2003, 10:23 PM
That quirk is a result of how the Date constructor is defined in ECMAScript, 3rd Edition.

whammy
02-08-2003, 11:37 PM
Whatever it is, I like it! :D

Alex, how far back do you think this will be compatible, browser-wise?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum