Javascript - 正则表达式验证日期格式 [英] Javascript - Regex to validate date format

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

问题描述

有没有办法在JavaScript中使用regex来验证多种格式的日期,例如:DD-MM-YYYY或DD.MM.YYYY或DD / MM / YYYY等?我需要所有这些在一个正则表达式,我不是很好用它。到目前为止,我已经想到了这个: var dateReg = / ^ \d {2} -\d {2} -\d {4} $ /; 对于DD-MM-YYYY。我只需要验证日期格式,而不是日期本身。

Is there any way to have a regex in JavaScript that validates dates of multiple formats, like: DD-MM-YYYY or DD.MM.YYYY or DD/MM/YYYY etc? I need all these in one regex and I'm not really good with it. So far I've come up with this: var dateReg = /^\d{2}-\d{2}-\d{4}$/; for DD-MM-YYYY. I only need to validate the date format, not the date itself.

推荐答案

你可以使用一个字符类( [./-] )以便分隔符可以是任何已定义的字符

You could use a character class ([./-]) so that the seperators can be any of the defined characters

var dateReg = /^\d{2}[./-]\d{2}[./-]\d{4}$/

或者更好的是,匹配第一个分隔符的字符类,然后将其作为一组捕获([./-])并使用对捕获的组 \1 的引用来匹配第二个分隔符,这将确保两个分隔符相同:

Or better still, match the character class for the first seperator, then capture that as a group ([./-]) and use a reference to the captured group \1 to match the second seperator, which will ensure that both seperators are the same:

var dateReg = /^\d{2}([./-])\d{2}\1\d{4}$/

"22-03-1981".match(dateReg) // matches
"22.03-1981".match(dateReg) // does not match
"22.03.1981".match(dateReg) // matches

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

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