From 0cb28f6bdfde0c60a58c4886043d8069a77e8d28 Mon Sep 17 00:00:00 2001 From: ravestack Date: Tue, 4 Aug 2015 02:22:15 -0400 Subject: [PATCH] Leap year and general date validation for isDate() --- test/validators.js | 11 +++++++++++ validator.js | 22 +++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/test/validators.js b/test/validators.js index 4cf642c24..10e537074 100644 --- a/test/validators.js +++ b/test/validators.js @@ -852,15 +852,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' ] }); diff --git a/validator.js b/validator.js index 8d2d155e5..1ef69b70f 100644 --- a/validator.js +++ b/validator.js @@ -450,7 +450,27 @@ }; validator.isDate = function (str) { - return !isNaN(Date.parse(str)); + var normalizedDate = new Date((new Date(str)).toUTCString()); + var dayOrYear, dayOrYearMatches, day, year; + if (isNaN(Date.parse(normalizedDate))) { + return false; + } + dayOrYearMatches = str.match(/[23]\d(\D|$)/g); + if (!dayOrYearMatches) { + return true; + } + dayOrYear = dayOrYearMatches.map(function(match) { + return match.slice(0,2); + }).join('/'); + day = String(normalizedDate.getUTCDate()); + year = String(normalizedDate.getFullYear()).slice(-2); + if (dayOrYear === day || dayOrYear === year) { + return true; + } else if ((dayOrYear === (day + '/' + year)) || (dayOrYear === (year + '/' + day))) { + return true; + } else { + return false; + } }; validator.isAfter = function (str, date) {