[英]JavaScript regular expression to get valid date format “MM/dd/yyyy”
I am learning JavaScript Regular Expression. 我正在学习JavaScript正则表达式。
I am writing a function to check valid date format, 'MM/dd/yyyy'. 我正在编写一个函数来检查有效的日期格式'MM / dd / yyyy'。
function isValidDate(dateStr) {
var result = dateStr.match(/^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/(199\d)|([2][0]\d{2})$/);
if(result)
return true;
return false;
}
It works fine, but I got some issues. 它工作正常,但出现了一些问题。
01/01/2014 // return true
01/1/2014 // return true (it should return false)
1/01/2014 // return true (it should return false)
I don't want the function to return true when the month.length is 1. I want to make sure that the month.length == 2 && the date.length == 2. How can I modify my regular expression? 我不希望该函数在month.length为1时返回true。我想确保month.length == 2 && date.length ==2。如何修改正则表达式?
EDIT 编辑
01/01/20 // return true (it should return false)
How can I make sure that the year.length == 4? 如何确定year.length == 4?
In your pattern, the leading zeros are optional because of the 'zero-or-one' quantifiers ( ?
). 在您的模式中,前导零是可选的,因为“零或一”量词(
?
)。 Simply remove them to make the zeros required. 只需将它们删除即可使所需的零。
Also, you need to wrap your year portion in a single group, and [2][0]
can be simplified to 20
. 另外,您需要将年份部分包装在一个组中,并且
[2][0]
可以简化为20
。 Try this: 尝试这个:
/^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(199\d|20\d{2})$/
Finally, You can simply use test
rather than match
: 最后,您可以简单地使用
test
而不是match
:
function isValidDate(dateStr) {
return /^(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])\/(199\d|20\d{2})$/.test(dateStr);
}
This will give you the results you want: 这将为您提供所需的结果:
isValidDate("01/01/2014")
→ true
isValidDate("01/01/2014")
→ true
isValidDate("01/1/2014")
→ false
isValidDate("01/1/2014")
→ false
isValidDate("1/01/2014")
→ false
isValidDate("1/01/2014")
→ false
尝试这个:
/^(0[1-9]|1[012])[\-\/\.](0[1-9]|[12][0-9]|3[01])[\-\/\.](19|20)\d\d$/
Here's what I'd go with: 这是我要去的:
/^(0)[1-9]{1}|(1)[0-2]{1}\\/([0-2]{1}[0-9]{1}|3[0-1]{1})\\/\\d{4}$/
It depends on your application -- you said you wanted four digit years, but didn't specify recent years, so I left out the restriction on dates being > 199* 这取决于您的应用程序-您说您希望输入四位数的年份,但未指定最近年份,因此我没有将日期限制在199以上*
You can test it here: http://regexr.com/39ae1 您可以在这里进行测试: http : //regexr.com/39ae1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.