Corey Ogburn Corey Ogburn - 1 month ago 12
Javascript Question

How can I disallow lenient dates in javascript?

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?

sln sln
Answer

They both can be validated with this.

 #  /^(?:(?:(?:19|20)\d\d[- \/.](?:0[1-9]|1[012])[- \/.](?:0[1-9]|[12][0-9]|3[01])T\d{2}:\d{2}:\d{2})|(?:(?:0[1-9]|1[012])[- \/.](?:0[1-9]|[12][0-9]|3[01])[- \/.](?:19|20)\d{2}))$/

 ^ 
 (?:
      (?:
           (?: 19 | 20 )
           \d\d [- /.] 
           (?: 0 [1-9] | 1 [012] )
           [- /.] 
           (?: 0 [1-9] | [12] [0-9] | 3 [01] )
           T \d{2} : \d{2} : \d{2} 
      )
   |  (?:
           (?: 0 [1-9] | 1 [012] )
           [- /.] 
           (?: 0 [1-9] | [12] [0-9] | 3 [01] )
           [- /.] 
           (?: 19 | 20 )
           \d{2} 
      )
 )
 $
Comments