Subject: Date Formats
This code has been in my toolbox for a few years. You could run different versions of it depending on the user’s browser settings
//============================
// Standard Date Validation Routine
//============================
function isValidDate(dateV, dateStr, fldName){
// Called by checkDate
// Checks for the following valid date formats:
// DD/MM/YY DD/MM/YYYY DD-MM-YY DD-MM-YYYY
// Also separates date into month, day, and year variables
var datePat = /^(\d{1,2})(/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
// To require a 4 digit year entry, use this line instead:
// var datePat = /^(\d{1,2})(/|-)(\d{1,2})\2(\d{4})$/;
var matchArray = dateStr.match(datePat); // is the format ok?
if (matchArray == null) {
alert(fldName+' is not in a valid format: Use dd/mm/yyyy or dd/mm/yy')
dateV.focus();
return false;
}
day = matchArray[1]; // parse date into variables
month = matchArray[3];
year = matchArray[4];
if (month < 1 || month > 12) { // check month range
alert(fldName+': Month must be between 1 and 12.');
dateV.focus();
return false;
}
if (day < 1 || day > 31) {
alert(fldName+' :Day must be between 1 and 31.');
dateV.focus();
return false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31) {
alert(fldName+": Month "+month+" doesn't have 31 days!");
dateV.focus();
return false;
}
if (month == 2) { // check for february 29th
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)) {
alert(fldName+": February " + year + " doesn't have " + day + " days!");
dateV.focus();
return false;
}
}
return true;
}
function checkDate(dateV, fldName, isNullAllowed){
//This is the function you call when validating a date field
var dateStr = dateV.value;
if(dateStr==“” ){
if (isNullAllowed){
return true;
} else {
alert(fldName+' must be completed');
return false;
}
} else {
return isValidDate(dateV, dateStr, fldName);
}
}