JavaScript isDate function to Validate Date formats

JavaScript isDate function to Validate Date formats

In an Employee Management System dashboard let’s assume we are fetching Employee Date of Joining from Database. While displaying this date in top left corner what I want is we required to validate the date for a specific format. In the below function I am checking 4 date formats. These are M/D/YYYY, MM/D/YYYY, M/DD/YYYY & MM/DD/YYYY.

JavaScript isDate function to Validate Date

/* 24 hrs * 60 mins * 60 seconds * 1000 ms */
var DAY_IN_MILLISECONDS = 86400000;
function isDate(d) {
var val = new String(d.value);
var char, len, i, sub, result, remainder;
var flag = 0;
if ((val.length >= 8) && (val.length <= 10)) {
len = val.length;
sub = new String(val.substr((len - 4), 4));
if (!(isNumeric(sub))) return false;
char = val.charAt(len - 5);
if (char != '/') return false;
char = val.charAt(len - 6);
if (!(isNumeric(char))) return false;
char = val.charAt(len - 7);
if (!(isNumeric(char))) {
if (char == '/') {
flag = 1;
} else return false;
}
char = val.charAt(len - 8);
if (!(isNumeric(char))) {
if (char != '/') return false;
if ((char == '/') & (flag == 1)) return false;
}
if (len > 8) {
remainder = len - 8;
sub = val.substr(0, remainder);
if (!(isNumeric(sub))) return false;
}
} else {
return false;
}
return true;
}