开发者

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)

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).

Second test is about date

DD.MM.YYYY

where DD is 2-digit representation of day, MM month and YYYY year - separated by dots. Can I also check is the date valid? So the user couldn't type 45.02.9999 for example.


This can be accomplished with fairly straightforward RegEx.

The first to test time in 24-hour format would be:

/(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. It's not smart enough to know how many days each month has (i.e. that 31.02.1999 is not a valid date), but should be good enough initial validation for most purposes.


In this post you have all the Regexp that you need.

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/


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. Then use n = str * 1 to convert to a number and check the range n >=0 && n <=23 in the first case.

The two pass approach means you can have a simpler regex and more readable code.


Use regex to split the string into its components then populate a date object with the result to check validity.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜