简体   繁体   English

验证 .NET 时间格式的正则表达式

[英]A regular expression to validate .NET time format

Background背景

I need to validate user input in some fields, where these are defining how to show time in some views.我需要在某些字段中验证用户输入,这些字段定义了如何在某些视图中显示时间。

Requirements要求

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 )时间格式必须以 Microsoft .NET 方式表示(如果您想了解有关框架的日期和时间格式的更多信息,请查看此 MSDN 库文章: 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.请记住,我正在寻找验证格式而不是实际时间字符串。

For example, user may input:例如,用户可以输入:

  • HH:mm高:毫米
  • hh:mm小时:毫米
  • ss ss
  • hh:ss hh:ss
  • mm:ss毫米:ss
  • ... and so on. ... 等等。

In fact, it should validate from the shortest to longest time format available.事实上,它应该从可用的最短到最长的时间格式进行验证。

Another point is I need to do it in client-side using JavaScript .另一点是我需要在客户端使用 JavaScript 来完成 In other words, any given regular expression by you should work in browsers JavaScript regular expressions' engine.换句话说,任何给定的正则表达式都应该在浏览器 JavaScript 正则表达式引擎中工作。

I'll appreciate any self-taylored one, any link or pasted expression!我会很感激任何自编的,任何链接或粘贴的表达!

Thank you in advance.先感谢您。

NOTE (Update)注意(更新)

I can't use ASP.NET validation engine, or any other.我不能使用 ASP.NET 验证引擎或任何其他验证引擎。 Because of project's requirements, I need to avoid that.由于项目的要求,我需要避免这种情况。

As far as I understand, there is no much options - sort of 20, as maximum.据我了解,没有太多选择 - 最多 20 个。 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>'

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.您可以区分大小写以区分M代表月和m代表分钟,并将其设为[hH]小时,然后将其设为[:-/]以允许使用不同的分隔符以及许多其他类似的东西。 But the main idea is to simply enumerate all options separated by |但主要思想是简单地枚举由|分隔的所有选项。 with just little amount of regex syntax between | |之间只有少量的正则表达式语法and || . .

What is your definition of a "valid" format string?您对“有效”格式字符串的定义是什么? Only once you know that can it be possible to validate a format string.只有知道了这一点,才能验证格式字符串。

"K" is also a valid format string “K”也是一个有效的格式字符串

"zz" is also a valid format string "zz" 也是一个有效的格式字符串

"e" is also a valid format (it would fall into the "The character is copied to the result string unchanged." case) “e”也是一个有效的格式(它会落入“字符被复制到结果字符串不变。”的情况下)

I'm not even sure what formats would actually cause .NET.ToString() to throw an exception (if that's what you are trying to avoid).我什至不确定什么格式实际上会导致 .NET.ToString() 抛出异常(如果这是您要避免的)。

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

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