Created
December 15, 2017 09:39
-
-
Save khanhtran3005/6cdd88f04ab45d96aac1105f9639dfa0 to your computer and use it in GitHub Desktop.
dd/mm/yyyy validation. Including leap year check
This file contains 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
function Validator() {} | |
Validator.min = function(number, min) { | |
return number >= min; | |
} | |
Validator.max = function(number, max) { | |
return number <= max; | |
} | |
Validator.between = function(number, min, max) { | |
return Validator.min(number, min) && Validator.max(number, max) | |
} | |
/** | |
* dd/mm/yyyy validation | |
* @param {string} date | |
* @return {boolean} | |
*/ | |
Validator.date = function(date) { | |
var regex = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/; | |
if (!regex.test(date)) return false; | |
var pdate = date.split('/'); | |
if (pdate.length < 3) pdate = date.split('-'); // if separator is not '/' | |
if (pdate < 3) return false; // check if array length < 3 | |
var d = parseInt(pdate[0]); | |
var m = parseInt(pdate[1]); | |
var y = parseInt(pdate[2]); | |
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; | |
if (!Validator.between(m, 1, 12)) return false; | |
if ((!(y % 4) && y % 100) || !(y % 400)) { | |
daysInMonth[1] = 29; // leap year | |
} | |
return d <= daysInMonth[--m]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment