試圖做這個日期驗證,這是我想出的代碼。它似乎沒有工作。任何幫助,將不勝感激。在JS中驗證日期?
function isValidDate(dateStr) {
// Checks for the following valid date formats:
// MM/DD/YY MM/DD/YYYY MM-DD-YY MM-DD-YYYY
var dateStr = document.getElementById("dob").value;
var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;
var matchArray = dateStr.match(datePat);
if (matchArray == null){
errMsg = errMsg + "Date is not in a valid format.";
result = false;
}
var month = matchArray[1];
var day = matchArray[3];
var year = matchArray[4];
if (month < 1 || month > 12){
errMsg = errMsg + "Month must be between 1 and 12.";
result = false;
}
if (day < 1 || day > 31){
errMsg = errMsg + "Day must be between 1 and 31.";
result = false;
}
if ((month==4 || month==6 || month==9 || month==11) && day==31){
errMsg = errMsg + "Month "+month+" doesn't have 31 days!";
result = false;
}
if (month == 2){ // check for leap year
var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
if (day>29 || (day==29 && !isleap)){
errMsg = errMsg + "February " + year + " doesn't have " + day + " days!";
result = false;
}
}
return result; // date is valid
}
格式的代碼,使其可讀 –
請解釋一下你的意思是「這是行不通的。」你在JavaScript控制檯中遇到任何錯誤嗎? – Blazemonger
@Blazemonger號顯示沒有錯誤。完全沒有任何反應。 –