您可以通过JavaScript验证日期的语法regular expressions。您可以使用Date对象检查语义,就像这样:
function ValidateCustomDate(d) {
var match = /^(\d{1,2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{4})$/.exec(d);
if (!match) {
// pattern matching failed hence the date is syntactically incorrect
return false;
}
var day = parseInt(match[1], 10); // radix (10) is required otherwise you will get unexpected results for 08 and 09
var month = {
Jan: 0,
Feb: 1,
Mar: 2,
Apr: 3,
May: 4,
Jun: 5,
Jul: 6,
Aug: 7,
Sep: 8,
Oct: 9,
Nov: 10,
Dec: 11
}[match[2]]; // there must be a shorter, simpler and cleaner way
var year = parseInt(match[3], 10);
var date = new Date(year, month, day);
// now, Date() will happily accept invalid values and convert them to valid ones
// 31-Apr-2011 becomes 1-May-2011 automatically
// therefore you should compare input day-month-year with generated day-month-year
return date.getDate() == day && date.getMonth() == month && date.getFullYear() == year;
}
console.log(ValidateCustomDate("1-Jan-2011")); // true
console.log(ValidateCustomDate("01-Jan-2011")); // true
console.log(ValidateCustomDate("29-Feb-2011")); // false
console.log(ValidateCustomDate("29-Feb-2012")); // true
console.log(ValidateCustomDate("31-Mar-2011")); // true
console.log(ValidateCustomDate("31-Apr-2011")); // false
验证该格式*看起来*右边是精细使用正则表达式,但使用正则表达式来验证日期实际上是一个有效的(什么用闰年,每月的天数不同等),正则表达式是错误的。 – Jamiec
[正则表达式匹配有效日期]的可能重复(http://stackoverflow.com/questions/51224/regular-expression-to-match-valid-dates) – Jamiec
你想要多久?你想赶上闰年?其他语言环境如何(“十月”与“Okt”等)? –