javascript javascript中用于日期验证的正则表达式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16462297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Regex for Date Validation in javascript
提问by User_MVC
pls can somebody give the date validation regex, which will allow the following rules are
请有人提供日期验证正则表达式,这将允许以下规则
- It should allow mm/dd/yyyy, m/d/yyyy, mm/d/yyyy, m/d/yyyy(not allow yy)
- Number of days for month (30 and 31) validation.
- Feb month validation for leap & non leap years.
- 它应该允许mm/dd/yyyy、m/d/yyyy、mm/d/yyyy、m/d/yyyy(不允许 yy)
- 月(30 和 31)验证的天数。
- 闰年和非闰年的二月验证。
采纳答案by Mr_Green
Try this:
试试这个:
([0-9][1-2])/([0-2][0-9]|[3][0-1])/((19|20)[0-9]{2})
and then if you got a valid string from the above regex then with string manipulations, do something like below:
然后如果你从上面的正则表达式中得到一个有效的字符串,然后进行字符串操作,请执行以下操作:
if(/([0-9][1-2])\/([0-2][0-9]|[3][0-1])\/((19|20)[0-9]{2})/.test(text)){
var tokens = text.split('/'); // text.split('\/');
var day = parseInt(tokens[0], 10);
var month = parseInt(tokens[1], 10);
var year = parseInt(tokens[2], 10);
}
else{
//show error
//Invalid date format
}
回答by Anirudha
Don't try to parse date entirelywith regex!Follow KISSprinciple..
不要尝试使用正则表达式完全解析日期!遵循KISS原则..
1>Get the dates with this regex
1>使用这个正则表达式获取日期
^(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})$
2> Validate month,year,day if the string matches with above regex!
2> 如果字符串与上面的正则表达式匹配,则验证月、年、日!
var match = myRegexp.exec(myString);
parseInt(match[0],10);//month
parseInt(match[1],10);//day
parseInt(match[2],10);//year
回答by ic3b3rg
Here's a full validation routine
这是一个完整的验证程序
var myInput = s="5/9/2013";
var r = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
if(!r.test(myInput)) {
alert("Invalid Input");
return;
}
var a = s.match(r), d = new Date(a[3],a[1] - 1,a[2]);
if(d.getFullYear() != a[3] || d.getMonth() + 1 != a[1] || d.getDate() != a[2]) {
alert("Invalid Date");
return;
}
// process valid date