使用正则表达式验证日期非常困难。例如,如何验证 2 月 29 日? (这个很难(硬!)
相反,我会使用内置的Date
目的。它总是会产生一个有效的日期。如果你这样做:
var date = new Date(2010, 1, 30); // 30 feb (doesn't exist!)
// Mar 02 2010
这样你就会知道它是无效的。您会看到它溢出到三月,这适用于所有参数。如果你的秒数是>59
它会溢出到几分钟等。
完整解决方案:
var value = "22.05.2013 11:23:22";
// capture all the parts
var matches = value.match(/^(\d{2})\.(\d{2})\.(\d{4}) (\d{2}):(\d{2}):(\d{2})$/);
//alt:
// value.match(/^(\d{2}).(\d{2}).(\d{4}).(\d{2}).(\d{2}).(\d{2})$/);
// also matches 22/05/2013 11:23:22 and 22a0592013,11@23a22
if (matches === null) {
// invalid
} else{
// now lets check the date sanity
var year = parseInt(matches[3], 10);
var month = parseInt(matches[2], 10) - 1; // months are 0-11
var day = parseInt(matches[1], 10);
var hour = parseInt(matches[4], 10);
var minute = parseInt(matches[5], 10);
var second = parseInt(matches[6], 10);
var date = new Date(year, month, day, hour, minute, second);
if (date.getFullYear() !== year
|| date.getMonth() != month
|| date.getDate() !== day
|| date.getHours() !== hour
|| date.getMinutes() !== minute
|| date.getSeconds() !== second
) {
// invalid
} else {
// valid
}
}
JSFiddle:http://jsfiddle.net/Evaqk/117/