Skip to content

Commit 8eacd50

Browse files
committed
Leap year and general date validation for isDate()
1 parent a08ec14 commit 8eacd50

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

test/validators.js

+11
Original file line numberDiff line numberDiff line change
@@ -852,15 +852,26 @@ describe('Validators', function () {
852852
validator: 'isDate'
853853
, valid: [
854854
'2011-08-04'
855+
, '2011-09-30'
855856
, '04. 08. 2011.'
856857
, '08/04/2011'
857858
, '2011.08.04'
858859
, '4. 8. 2011. GMT'
860+
, '2. 28. 2011. GMT'
861+
, '2. 29. 2008. GMT'
862+
, '2. 29. 1988. GMT'
859863
, '2011-08-04 12:00'
864+
, '2/29/24'
865+
, '2-29-24'
860866
]
861867
, invalid: [
862868
'foo'
863869
, '2011-foo-04'
870+
, '2011-09-31'
871+
, '2. 29. 1987. GMT'
872+
, '2. 29. 2011. GMT'
873+
, '2/29/25'
874+
, '2-29-25'
864875
, 'GMT'
865876
]
866877
});

validator.js

+27-1
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,33 @@
450450
};
451451

452452
validator.isDate = function (str) {
453-
return !isNaN(Date.parse(str));
453+
var normalizedDate = new Date((new Date(str)).toUTCString());
454+
var regularDay = String(normalizedDate.getDate());
455+
var utcDay = String(normalizedDate.getUTCDate());
456+
var dayOrYear, dayOrYearMatches, year;
457+
if (isNaN(Date.parse(normalizedDate))) {
458+
return false;
459+
}
460+
//check for valid double digits that could be late days
461+
//check for all matches since a string like '12/23' is a valid date
462+
dayOrYearMatches = str.match(/[23]\d(\D|$)/g);
463+
if (!dayOrYearMatches) {
464+
return true;
465+
}
466+
dayOrYear = dayOrYearMatches.map(function(match) {
467+
return match.slice(0,2);
468+
}).join('/');
469+
year = String(normalizedDate.getFullYear()).slice(-2);
470+
//local date and UTC date can differ, but both are valid, so check agains both
471+
if (dayOrYear === regularDay || dayOrYear === utcDay || dayOrYear === year) {
472+
return true;
473+
} else if ((dayOrYear === (regularDay + '/' + year)) || (dayOrYear === (year + '/' + regularDay))) {
474+
return true;
475+
} else if ((dayOrYear === (utcDay + '/' + year)) || (dayOrYear === (year + '/' + utcDay))) {
476+
return true;
477+
} else {
478+
return false;
479+
}
454480
};
455481

456482
validator.isAfter = function (str, date) {

0 commit comments

Comments
 (0)