如何以两种格式(mm-dd-yy和mm / dd / yy)验证日期,目前以下代码仅验证(mm-dd-yy)
function isValidDate(dateString) {
if (!/^\d{2}\-\d{2}\-\d{2}$/.test(dateString)) {
return false;
}
var parts = dateString.split("-");
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
if (month == 0 || 12 < month) {
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return (0 < day && day <= monthLength[month - 1]);
}
答案 0 :(得分:0)
将正则表达式更改为
function isValidDate(dateString) {
// use - or / as the seprator
if (!/^\d{2}([-\/])\d{2}\1\d{2}$/.test(dateString)) {
return false;
}
//split using - or /
var parts = dateString.split(/[-\/]/);
var day = parseInt(parts[1], 10);
var month = parseInt(parts[0], 10);
if (month == 0 || 12 < month) {
return false;
}
var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
return (0 < day && day <= monthLength[month - 1]);
}
答案 1 :(得分:0)
此模式将验证日期格式(mm / dd / yy)
private static final String DATE_PATTERN =
"((0?[1-9]|1[012])/0?[1-9]|[12][0-9]|3[01])/(\\d\\d))";