使用JavaScript正则表达式验证日期的问题 [英] Problems using javascript regex to validate date

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

问题描述

我正在尝试使用JavaScript正则表达式来验证日期输入,但是将有效日期返回为无效。我不是正则表达式的专家,所以我不知道有什么问题:

I'm trying to use javascript regex to validate a date input, but it is returning valid dates as invalid. I'm not an expert on regex so I don't know what is wrong with it:

/^([0-9]d{2})+(\.|-|\/)+([0-9]d{2})+(\.|-|\/)+([0-9]d{4})+$/

我希望接受这些日期格式:

I want these date formats to be accepted:

23/04/2001

23/04/2001

23-04-2001

23-04-2001

23.04.2001

23.04.2001

最初我是这样,但是它像其他角色接受日期,像23/04 / 2001jhsdgf:

Originally I had this, but it was accepting dates with other characters on the end like 23/04/2001jhsdgf:

/\d{2}(\.|-|\/)\d{2}(\.|-|\/)\d{4}/;


推荐答案

取您的原始正则表达式,只需添加 ^ $ 从你的新的。问题解决了。

Take your original regex and just add the ^ and $ from your new one to it. Problem solved.

编辑:虽然,真的,(\。| - | \ /)一个混乱,应该是 [。\ / - ]

Although, really, the (\.|-|\/) is a mess and should be [.\/-] instead.

编辑2:第一个([。\ / - ])然后你可以用 \1 然后它需要两个分隔符相同。

EDIT 2: That said, if you make the first one ([.\/-]) then you can replace the second one with \1 and then it would require both separators to be the same.

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

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