Skip to content

Instantly share code, notes, and snippets.

@anova
Created October 16, 2014 20:22
Show Gist options
  • Save anova/1eb5721e17b62522be34 to your computer and use it in GitHub Desktop.
Save anova/1eb5721e17b62522be34 to your computer and use it in GitHub Desktop.
Useful function for string -> date validation.
;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