Created
October 16, 2014 20:22
-
-
Save anova/1eb5721e17b62522be34 to your computer and use it in GitHub Desktop.
Useful function for string -> date validation.
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 isDate(value) { | |
try { | |
//Change the below values to determine which format of date you wish to check. It is set to dd/mm/yyyy by default. | |
var YearIndex = 2; | |
var MonthIndex = 1; | |
var DayIndex = 0; | |
value = value.replace(/-/g, "/").replace(/\./g, "/"); | |
var SplitValue = value.split("/"); | |
var OK = true; | |
if (!(SplitValue[DayIndex].length == 1 || SplitValue[DayIndex].length == 2)) { | |
OK = false; | |
} | |
if (OK && !(SplitValue[MonthIndex].length == 1 || SplitValue[MonthIndex].length == 2)) { | |
OK = false; | |
} | |
if (OK && SplitValue[YearIndex].length != 4) { | |
OK = false; | |
} | |
if (OK) { | |
var Day = parseInt(SplitValue[DayIndex], 10); | |
var Month = parseInt(SplitValue[MonthIndex], 10); | |
var Year = parseInt(SplitValue[YearIndex], 10); | |
if (OK = ((Year > 1900) && (Year < new Date().getFullYear()))) { | |
if (OK = (Month <= 12 && Month > 0)) { | |
var LeapYear = (((Year % 4) == 0) && ((Year % 100) != 0) || ((Year % 400) == 0)); | |
if (Month == 2) { | |
OK = LeapYear ? Day <= 29 : Day <= 28; | |
} | |
else { | |
if ((Month == 4) || (Month == 6) || (Month == 9) || (Month == 11)) { | |
OK = (Day > 0 && Day <= 30); | |
} | |
else { | |
OK = (Day > 0 && Day <= 31); | |
} | |
} | |
} | |
} | |
} | |
return OK; | |
} | |
catch (e) { | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment