简体   繁体   English

检查特定格式(时间和日期)

[英]Check for specific formatting (time and date)

I need to test in javascript the following formats (so I have a string and I must check if it's valid or not) 我需要在javascript中测试以下格式(所以我有一个字符串,我必须检查它是否有效)

XX:XX

value must be two integer (with two digits) separated by colon , the first one must be 0-23 and second 0-59 (it's about time). 值必须是2点的整数 (用两位数字)由冒号分开,第一个必须是0-23和0-59秒(它是关于时间)。

Second test is about date 第二次测试是关于约会的

DD.MM.YYYY

where DD is 2-digit representation of day, MM month and YYYY year - separated by dots. 其中DD是日,MM月和YYYY年的2位数表示 - 以点分隔。 Can I also check is the date valid ? 我还可以检查日期是否有效 So the user couldn't type 45.02.9999 for example. 因此用户无法输入45.02.9999。

In this post you have all the Regexp that you need. 在这篇文章中,您拥有所需的所有正则表达式。

http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5 http://regexlib.com/DisplayPatterns.aspx?cattabindex=4&categoryId=5

this is for time: 这是时间:

^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$

this is for date: 这是为了约会:

^(0[1-9]|[12][0-9]|3[01]).([1][0-12]|[0][1-9]).(19|20)\d\d$

you can try this regexp in http://www.rubular.com/ 你可以在http://www.rubular.com/试试这个正则表达式

This can be accomplished with fairly straightforward RegEx. 这可以通过相当简单的RegEx来完成。

The first to test time in 24-hour format would be: 第一个以24小时格式测试时间的是:

/(0[1-9]|1[1-9]|2[1-3]):[0-5][1-9]/.test(yourTime);

The second to test date would be: 第二个测试日期是:

/([0-2][0-9]|3[0-1])\.(0[1-9]|1[0-2])\.(19[0-9][0-9]|20[0-1][0-9])/.test(yourDate);

Which will allow dates up until 31.12.2019. 这将允许日期到2017年12月31日。 It's not smart enough to know how many days each month has (ie that 31.02.1999 is not a valid date), but should be good enough initial validation for most purposes. 知道每个月有多少天(即31.02.1999不是有效日期)并不够聪明,但对于大多数目的来说应该是足够好的初始验证。

Use a two pass approach. 使用两遍方法。 First use a regex to check the general structure of the string to make sure it has the correct delimiters and digits in the right place. 首先使用正则表达式检查字符串的一般结构,以确保它在正确的位置具有正确的分隔符和数字。 In the second pass you can use indexOf() to find delimiters and substring() to extract the numbers in each position. 在第二遍中,您可以使用indexOf()来查找分隔符,并使用substring()来提取每个位置中的数字。 Then use n = str * 1 to convert to a number and check the range n >=0 && n <=23 in the first case. 然后使用n = str * 1转换为数字,并在第一种情况下检查范围n >=0 && n <=23

The two pass approach means you can have a simpler regex and more readable code. 两遍方法意味着您可以使用更简单的正则表达式和更易读的代码。

使用正则表达式将字符串拆分为其组件,然后使用结果填充日期对象以检查有效性。

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

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