Last active
December 13, 2015 22:09
-
-
Save ye/4982766 to your computer and use it in GitHub Desktop.
Validate Date Range (From - To).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dv = function(date){ | |
var matches = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/.exec(date); | |
if (matches == null) return {'isValid': false}; | |
var m = matches[1] - 1; | |
var d = matches[2]; | |
var y = matches[3]; | |
var cd = new Date(y, m, d); | |
var isValid = (cd.getDate() == d) && (cd.getMonth() == m) && (cd.getFullYear() == y); | |
return {'isValid': isValid, 'month':m, 'day':d, 'year':y} | |
}; | |
var range_validate = function(from_date, to_date){ | |
var d1 = dv(from_date); | |
var d2 = dv(to_date); | |
return d1.isValid && d2.isValid && ( | |
d1.year < d2.year || | |
( d1.year == d2.year && | |
( d1.month < d2.month || | |
(d1.month == d2.month && d1.day < d2.day) | |
) | |
) | |
); | |
}; | |
console.log( dv('02/26/2013') ); // valid | |
console.log( range_validate('02/26/2013', '03/06/2013') ); // true | |
console.log( range_validate('03/26/2013', '03/06/2013') ); // false | |
// unit tests | |
(function(){ | |
var M_DAYS = [31,28,31,30,31,30,31,31,30,31,30,31]; | |
var genRandom = function(range, start){ | |
var offset = start ? start : 0; | |
return Math.floor((Math.random() * range) + offset); | |
}; | |
var year = genRandom(2015-1900, 1900); | |
var leap_year = (0 == year % 400) || (0 == year % 4 && 0 != year % 100); | |
if (leap_year) { M_DAYS[1] += 1; } | |
var month = genRandom(12, 1); | |
var day = genRandom(M_DAYS[month-1], 1); | |
console.log(month + '/' + day + '/' + year); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment