普通防爆pression检测YYYY-MM-DD [英] Regular Expression to detect yyyy-MM-dd

查看:142
本文介绍了普通防爆pression检测YYYY-MM-DD的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用asp.net 4和C#。

I use asp.net 4 and c#.

我需要使用类型验证的Web控件即 RegularEx pressionValidator 来检测一个TextBox inputed数据格式YYYY IS NOT -MM-DD (字符串)。

I need to use a WebControl of type Validation namely RegularExpressionValidator to detect data inputed in a TextBox that IS NOT in format yyyy-MM-dd (String).

不知道如何写正则表达式来申请这个加时赛控制?

Any idea how to write the RegEx to apply ot this control?

感谢

推荐答案

下面是一个可能的正则表达式:

Here's one possible regex:

^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$

请注意:这将prevent个月> 12天及> 31,但不会检查特定的长度个月(即它不会阻止2月30日或4月31日)。您的可能的写一个正则表达式来做到这一点,但是这将是非常漫长的,而二月二十九日总是要给你的正则表达式的问题。

Note: this will prevent months >12 and days >31, but won't check specific months for length (ie it won't block 30th Feb or 31st Apr). You could write a regex to do that, but it would be quite lengthy, and 29th Feb is always going to give you problems in regex.

我说,如果你需要的那种精细的验证,你最好解析带有日期库的日期;正则表达式是不是你的工具。这正则表达式应该是足够的基本pre-验证虽然。

I'd say if you need that kind of fine-grained validation, you're better off parsing the date with a date library; regex isn't the tool for you. This regex should be sufficient for basic pre-validation though.

我也走了上年度宽松;只是检查它的四位数字。但是,如果你需要某种完整性检查(一定范围内IE),应该不会太难补充。敌人例如,如果你想在本世纪只匹配的日期,你将取代 \\ D {4} 的正则表达式的开头 20 \\ D {2} 。同样,试图验证与正则表达式过多精度的日期将是困难的,你应该使用最新的解析器,但你可以得到基本的世纪级很容易匹配到prevent进入什么真正愚蠢的用户。

I've also gone lenient on the year; just checking that it's four digits. But if you want some sort of sanity check (ie within certain bounds), it shouldn't be too hard to add. Foe example, if you want to match only dates in the this century, you would replace the \d{4} at the beginning of the regex with 20\d{2}. Again, trying to validate a date with excessive accuracy in regex is going to be difficult and you should use a date parser, but you can get basic century-level matching quite easily to prevent the user entering anything really silly.

最后,我已经把 ^ $ 来扎断弦的两端,以便它可以' ŧ如果用户输入一个有效的日期和多余的字符,以及相匹配。 (您可能要添加一个字符串长度的验证此也)。

Finally, I've put ^ and $ to tie off the ends of the string so it can't match if the user enters a valid date and extra characters as well. (You may want to add a string length validator for this as well).

希望有所帮助。

这篇关于普通防爆pression检测YYYY-MM-DD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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