Skip to content

Commit

Permalink
Leap year and general date validation for isDate().
Browse files Browse the repository at this point in the history
  • Loading branch information
ravestack committed Sep 27, 2015
1 parent fc03288 commit ff4d907
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
7 changes: 7 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -860,6 +860,13 @@ describe('Validators', function () {
, '2011.08.04'
, '4. 8. 2011. GMT'
, '2011-08-04 12:00'
, '2/29/24'
, '2-29-24'
, '12'
, '11/2/23 12:24'
, new Date()
, 'Mon Aug 17 2015 00:24:56 GMT-0500 (CDT)'
, '2/22/23 23:24:26'
]
, invalid: [
'foo'
Expand Down
32 changes: 31 additions & 1 deletion validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -468,7 +468,37 @@
};

validator.isDate = function (str) {
return !isNaN(Date.parse(str));
var normalizedDate = new Date((new Date(str)).toUTCString());
var regularDay = String(normalizedDate.getDate());
var utcDay = String(normalizedDate.getUTCDate());
var dayOrYear, dayOrYearMatches, year;
if (isNaN(Date.parse(normalizedDate))) {
return false;
}
if (typeof str !== 'string') {
return true; //if Date.parse() passes, it's the current time
}
//check for valid double digits that could be late days
//check for all matches since a string like '12/23' is a valid date
//ignore everything with nearby colons
dayOrYearMatches = str.match(/(^|[^:])[23]\d([^:\d]|$)/g);
if (!dayOrYearMatches) {
return true;
}
dayOrYear = dayOrYearMatches.map(function(digitString) {
return digitString.match(/\d+/g)[0];
}).join('/');
year = String(normalizedDate.getFullYear()).slice(-2);
//local date and UTC date can differ, but both are valid, so check agains both
if (dayOrYear === regularDay || dayOrYear === utcDay || dayOrYear === year) {
return true;
} else if ((dayOrYear === (regularDay + '/' + year)) || (dayOrYear === (year + '/' + regularDay))) {
return true;
} else if ((dayOrYear === (utcDay + '/' + year)) || (dayOrYear === (year + '/' + utcDay))) {
return true;
} else {
return false;
}
};

validator.isAfter = function (str, date) {
Expand Down

0 comments on commit ff4d907

Please sign in to comment.