0

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.

4 Answers 4

1

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.

1

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/

2
  • A regex can't check the validity. There is no way a regex can catch an invalid date such as 29.02.2011
    – Stephen P
    Mar 1, 2011 at 0:46
  • 1
    @Stephen P You haven't heard of Gregorian Compatible Regular Expressions? :P
    – alex
    Mar 1, 2011 at 0:50
0

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.