I'm trying to validate if a string is a valid date. Date.parse(dateString) or new Date(dateString) both are very lenient. For example a date like 14/14/2000 is coming out as 2/14/2001. I tried a regular expression but now I'm needing to validate more than mm/dd/yyyy, I also need to validate yyyy-mm-ddThh:mm:ss e.g. 1951-02-05T00:00:00.
I was using regular expressions and some basic date checks right now, but the second date format above is failing the regex.
function isDate(dateToCheck) {
if (dateToCheck == "" || dateToCheck == null) { return true; }
var timestamp = Date.parse(dateToCheck);
var d = new Date(timestamp);
var re = /(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d/;
var valid = re.test(dateToCheck);
valid = valid && !isNaN(timestamp);
valid = valid && d.getFullYear() > 1900 && d.getFullYear() < 2100;
return valid;
}
The regex is specifically for mm/dd/yyyy where month and day are both double digits (single digit months get a leading zero) and won't allow invalid months or days like 14 as a month or 32 as a day. The year can be anything from 1900 to 2099.
It's not air tight. It would allow 02/31/2000 which is invalid because February never has 31 days.
How can I validate both of these date formats without allowing lenient dates?
Date.parse('14/14/2000')returnsNaN- Fiddle. Date.parse returns an integer conversion of the date you provide it. If it isNaN, the date is invalid.new Data('14/14/2000')returnsInvalid Date. - BicDate.parse('14/14/2000')in IE10 returns982134000000. I cannot trust it for an internal website that will only run on IE10. - Corey Ogburn