用正則表達式驗證日期非常困難。例如,你如何驗證2月29日? (很難!)
而是我會使用內置的Date
對象。它將始終生成有效的日期。如果你這樣做:
var date = new Date(2010, 1, 30); // 30 feb (doesn't exist!)
// Mar 02 2010
所以你會知道它是無效的。你看它溢出到3月份,這對所有參數都適用。如果你秒>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,[email protected]
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/
你從哪裏得到模式表單?爲什麼有'[0,1]'?這將不會允許'22.05.2013'。 – putvande
@putvande從這裏http://stackoverflow.com/questions/16626942/javascript-regex-validate-date-time – Happy
你的正則表達式在日期中使用斜槓而不是點 – ahmad