在JS中使用正则表达式检查日期格式 [英] Check dateformat with regex in JS
本文介绍了在JS中使用正则表达式检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
validateForLongDateTime('22 -03-1981')
函数validateForLongDateTime(date){
var regex = new RegExp(/ ^ \d {2} [.- /] \d {2} [.- / ] \d {4} $ /);
var dateOk = regex.test(date);
if(dateOk){
alert('ok');
} else {
alert('notok');
}
}
解决方案
正则表达式至少有两个问题:
- 它没有转义正斜杠
- 字符类中的连字符是未转义的,并形成一个范围(仅匹配
。
和/
)这不是在这里需要的。
固定正则表达式将如下所示:
/ ^ \d {2} [。\ / - ] \d {2} [。\ / - ] \d {4} $ /
请参阅演示
但是,您无法验证日期,因为它也匹配 37-67-5734
。
- 以下是一个SO帖子具有全面的正则表达式方法,看起来v iable
这里是我的enahanced版本与分隔符的字符类:
^(?:(?:31 [\ /.-])(?:0?[13578] | 1 [02]))\1 |(?:(?:29 | 30)([\ /.-])(?: 0 ?[1,3-9] | 1 [0-2])\2))(?:(?:1 [6-9] | [2-9] \d)?\d {2} )$ | ^(?:29([\ /.-])0?2\3(?:(?:(?:1 [6-9] | [2-9] \d)? (00))))$(0) | ^(?: 0?[1-9] | 1\d | 2 [0-8])([\ /.-])(?:(?:0?[1-9])|( ?:1 [0-2]))\4(?:(?:1 [6-9] | [2-9] \d)?\d {2})$
- 这里是使用
Date.parse
My question is simple but takes work. I tried lots of regex expressions to check my datetime is ok or not, but though I am sure my regex exprerssion is correct it always return to me isnotok with ALERT. Can you check my code?
validateForLongDateTime('22-03-1981')
function validateForLongDateTime(date){
var regex=new RegExp("/^\d{2}[.-/]\d{2}[.-/]\d{4}$/");
var dateOk=regex.test(date);
if(dateOk){
alert('ok');
}else{
alert('notok');
}
}
解决方案
There are at least 2 issues with the regex:
- It has unescaped forward slashes
- The hyphen in the character classes is unescaped and forms a range (matching only
.
and/
) that is not what is necessary here.
The "fixed" regex will look like:
/^\d{2}[.\/-]\d{2}[.\/-]\d{4}$/
See demo
However, you cannot validate dates with it since it will also match 37-67-5734
.
- Here is an SO post with a comprehensive regex approach that looks viable
Here is my enahanced version with a character class for the delimiter:
^(?:(?:31([\/.-])(?:0?[13578]|1[02]))\1|(?:(?:29|30)([\/.-])(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29([\/.-])0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])([\/.-])(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$
- Here is an SO post showing another approach using
Date.parse
这篇关于在JS中使用正则表达式检查日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文