使用javascript和regex验证日期时间 [英] validate datetime with javascript and regex
问题描述
我正在尝试使用有效的日期时间格式验证文本框。我需要检查24小时日期时间格式。所以我在文本框中输入以下文字 22.05.2013 11:23:22
I am trying to validate textbox with valid datetime format. I need to check 24 hours datetime format. So i input following text to my textbox 22.05.2013 11:23:22
但它仍然没有验证它正确。我是正则表达式的新手。到目前为止,我已经尝试了
But it still doesnt validate it correctly. I am totally new to regex. This is so far i have tried
$('#test1').blur(function(){
var validTime = $(this).val().match(/^[0,1]?\d\/(([0-2]?\d)|([3][01]))\/((199\d)|([2-9]\d{3}))\s[0-2]?[0-9]:[0-5][0-9]?$/);
debugger;
if (!validTime) {
$(this).val('').focus().css('background', '#fdd');
} else {
$(this).css('background', 'transparent');
}
});
这是我的小提琴
推荐答案
用正则表达式验证日期非常困难。例如,您如何验证2月29日? (这很难!)
It's very hard to validate a date with a regular expression. How do you validate 29th of February for instance? (it's hard!)
相反,我会使用内置的 Date
对象。它总是会生成一个有效的日期。如果你这样做:
Instead I would you use the built-in Date
object. It will always produce a valid date. If you do:
var date = new Date(2010, 1, 30); // 30 feb (doesn't exist!)
// Mar 02 2010
所以你会知道它是无效的。你看它溢出到三月,这适用于所有参数。如果您的秒数> 59
,它将溢出到几分钟等。
So you'll know it's invalid. You see it overflows to March, this works for all the parameters. If your seconds is >59
it will overflow to minutes etc.
完整解决方案:
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/
JSFiddle: http://jsfiddle.net/Evaqk/117/
这篇关于使用javascript和regex验证日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!