在JS中使用正则表达式检查日期格式 [英] Check dateformat with regex in JS

查看:149
本文介绍了在JS中使用正则表达式检查日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题很简单,但需要工作。我尝试了很多正则表达式来检查我的datetime是否可以,但是我确信我的正则表达式exprssion是正确的,它总是返回给我的isnotok与ALERT。你可以检查我的代码吗?

  
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





这里是我的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})$ 




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 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})$

这篇关于在JS中使用正则表达式检查日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆