Skip to content

Commit

Permalink
Merge pull request #418 from ravestack/suchchange
Browse files Browse the repository at this point in the history
Leap year and general date validation for isDate()
  • Loading branch information
chriso committed Aug 15, 2015
2 parents 57daf39 + 8eacd50 commit cc7071f
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
11 changes: 11 additions & 0 deletions test/validators.js
Original file line number Diff line number Diff line change
Expand Up @@ -855,15 +855,26 @@ describe('Validators', function () {
validator: 'isDate'
, valid: [
'2011-08-04'
, '2011-09-30'
, '04. 08. 2011.'
, '08/04/2011'
, '2011.08.04'
, '4. 8. 2011. GMT'
, '2. 28. 2011. GMT'
, '2. 29. 2008. GMT'
, '2. 29. 1988. GMT'
, '2011-08-04 12:00'
, '2/29/24'
, '2-29-24'
]
, invalid: [
'foo'
, '2011-foo-04'
, '2011-09-31'
, '2. 29. 1987. GMT'
, '2. 29. 2011. GMT'
, '2/29/25'
, '2-29-25'
, 'GMT'
]
});
Expand Down
28 changes: 27 additions & 1 deletion validator.js
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,33 @@
};

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;
}
//check for valid double digits that could be late days
//check for all matches since a string like '12/23' is a valid date
dayOrYearMatches = str.match(/[23]\d(\D|$)/g);
if (!dayOrYearMatches) {
return true;
}
dayOrYear = dayOrYearMatches.map(function(match) {
return match.slice(0,2);
}).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 cc7071f

Please sign in to comment.