用于验证 .NET 时间格式的正则表达式 [英] A regular expression to validate .NET time format
问题描述
背景
我需要在某些字段中验证用户输入,这些字段定义了如何在某些视图中显示时间.
I need to validate user input in some fields, where these are defining how to show time in some views.
要求
时间格式必须以 Microsoft .NET 方式表示(如果您想了解有关框架日期和时间格式的更多信息,请查看这篇 MSDN 库文章:http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)
Time format must be expressed in Microsoft .NET way (check this MSDN Library article if you want to learn more about framework's date and time formatting: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx)
请记住,我希望验证格式而不是实际的时间字符串.
Keep in mind I'm looking to validate the format instead of an actual time string.
例如,用户可以输入:
- 时:毫米
- 时:分
- ss
- hh:ss
- 毫米:秒
- ...等等.
事实上,它应该从可用的最短到最长的时间格式进行验证.
In fact, it should validate from the shortest to longest time format available.
另一点是我需要在客户端使用 JavaScript.换句话说,任何给定的正则表达式都应该在浏览器的 JavaScript 正则表达式引擎中工作.
Another point is I need to do it in client-side using JavaScript. In other words, any given regular expression by you should work in browsers JavaScript regular expressions' engine.
我会欣赏任何自创的,任何链接或粘贴的表达!
I'll appreciate any self-taylored one, any link or pasted expression!
提前致谢.
注意(更新)
我无法使用 ASP.NET 验证引擎或任何其他引擎.由于项目的要求,我需要避免这种情况.
推荐答案
据我所知,没有太多选择 - 最多 20 种.为什么不把它们全部列举在一个大的正则表达式中而不用太多特殊符号呢?喜欢
As far as I understand, there is no much options - sort of 20, as maximum. Why not just enumerate them all in one big regex without much special symbols? Like
'hh:mm|hh:mm:ss|yyyy-MM-dd hh:mm|<etc>'
您可以区分大小写,以区分月份的 M
和分钟的 m
,以及区分小时的 [hH]
,然后将它设置为 [:-/]
那里你允许不同的分隔符,以及许多其他类似的东西.但主要思想是简单地枚举由 |
分隔的所有选项,在 |
和 |
之间使用少量的正则表达式语法.
you could than make it case sensitive to differentiate between M
for month and m
for minute, and for hours make it [hH]
, then make it [:-/]
there where you allow for different separators, and lots of other similar things. But the main idea is to simply enumerate all options separated by |
with just little amount of regex syntax between |
and |
.
这篇关于用于验证 .NET 时间格式的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!