For a few days now, I have been battling with the problem of JavaScript date validation. I wanted to validate text inputed by a user as they were typing to tell them if it was a valid date. After much searching on the internet, I found nothing that worked. So I wrote the following code to do the job, it is a simple but effective
isDate
function:
function isDate(value, sepVal, dayIdx, monthIdx, yearIdx) {
try {
var DayIndex = dayIdx !== undefined ? dayIdx : 0;
var MonthIndex = monthIdx !== undefined ? monthIdx : 0;
var YearIndex = yearIdx !== undefined ? yearIdx : 0;
value = value.replace(/-/g, "/").replace(/\./g, "/");
var SplitValue = value.split(sepVal || "/");
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(OK = Day > 0)
{
if (Month == 2) {
OK = LeapYear ? Day <= 29 : Day <= 28;
}
else {
if ((Month == 4) || (Month == 6) || (Month == 9) || (Month == 11)) {
OK = Day <= 30;
}
else {
OK = Day <= 31;
}
}
}
}
}
}
return OK;
}
catch (e) {
return false;
}
}
Just copy the above function and call
isDate(value)
where value is a
string
containing a valid or invalid date. The function returns a bool
true
if the
string
was a date and
false
if it wasn't. Hope this helps!
" />
EDIT: Thanks to Member 2792937 for bringing a bug to my attention.
Both parseInt('08')
and parseInt('09')
return zero because the function tries to determine the correct base for the numerical system used. In JavaScript, numbers starting with zero are considered octal and there's no 08 or 09 in octal, hence the problem.
To fix this, just add the second parameter for parseInt
, the base to be used for the conversion. The correct calls should be parseInt('08', 10)
and parseInt('09', 10)
.
(From http://www.ventanazul.com/webzine/articles/issues-parseint-javascript[^])
I have modified my code to fix this issue.
EDIT: Now includes optional parameters for specifying separator value and the indexes. To miss out a parameter simply pass in undefined. Thanks to
Lester Callif for the suggestions.