简体   繁体   English

如何验证这种格式的日期(dd \\ mm \\ yyyy)

[英]How do I validate a date in this format (dd\mm\yyyy)

i have this function: 我有这个功能:

var isValidDate = function (date) {
   var regEx = /^\d{2}\\d{2}\\d{4}$/;
   return date.match(regEx) !== null;
};

I want to validate my date with this form : 我想用以下表格验证我的日期:

23/01/2015 2015年2月23日

My question is my REGEX it is good ..? 我的问题是我的REGEX好吗?

You can use: 您可以使用:

var regEx = /^\d{2}\\\d{2}\\\d{4}$/;

A backslash also requires escaping. 反斜杠也需要转义。

Also note that your original string also needs to have \\\\ for a literal backslash like this: 还要注意,您的原始字符串也需要使用\\\\来表示这样的文字反斜杠:

var matched = regEx.test('15\\11\\2015')
//=> true

For matching dd/mm/yyyy regex would be just: 为了匹配dd/mm/yyyy正则表达式将是:

var regEx = /^\d{2}\/\d{2}\/\d{4}$/;

This however would still not invalidate wrong dates like 13/13/2015 但是,这仍然不会使错误的日期无效,例如13/13/2015

The regex is not safe. 正则表达式不安全。 Consider 99/99/9999 , an improved regex could read /^[0-3]\\d\\/[01]\\d\\/[12]\\d{3}$/. However this still accept dates like 考虑到99/99/9999 ,改进的正则表达式可以读取/^[0-3]\\d\\/[01]\\d\\/[12]\\d{3}$/. However this still accept dates like /^[0-3]\\d\\/[01]\\d\\/[12]\\d{3}$/. However this still accept dates like 39/19/2999` which is clearly illeagal. /^[0-3]\\d\\/[01]\\d\\/[12]\\d{3}$/. However this still accept dates like 39/19 / 2999`的/^[0-3]\\d\\/[01]\\d\\/[12]\\d{3}$/. However this still accept dates like ,这显然是非法的。

While you can refine your regex further to limit the seperate numbers to valid ranges it becomes rather complex if you want to rule out feb 31. I recommend doing this with actual code rather than a regex. 虽然可以进一步完善正则表达式以将单独的数字限制为有效范围,但是如果要排除2月31日,则变得相当复杂。我建议使用实际代码而不是正则表达式来执行此操作。

You may use html5 pattern . 您可以使用html5 pattern better pattern ^([0-2]\\d|3[0-1])\\\\(0\\d|1[0-2])\\\\[1-2]\\d{3}$ . 更好的模式^([0-2]\\d|3[0-1])\\\\(0\\d|1[0-2])\\\\[1-2]\\d{3}$ it will also work in regex.. 它也将在正则表达式中工作。

 <input type="text" pattern="^\\d{2}\\\\\\d{2}\\\\\\d{4}$" /><br/> better <input type="text" pattern="^([0-2]\\d|3[0-1])\\\\(0\\d|1[0-2])\\\\[1-2]\\d{3}$" /> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM