FatRat
FatRat

Reputation: 71

Regular expression to validate time until 04:00

Hello I have this ^([02][0-4])(:[0-5]\d){1,2}$ expression for checking time in a form. My problem is that the maximum that I can input should be 04:00 and not 04:59 but of course including all the other numbers like 02:47 or 03:59.
I never used regex, that's the best I could do can someone help me or at least explain me?
Any help apprecciated, thanks

Upvotes: 2

Views: 60

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521914

You could use an alternation to include 04:00 as an edge case:

^(0[0-3]:[0-5][0-9]|04:00)$

Demo

Edit:

If you want to exclude 00:00 proper from being included, then we have to do more work, but we can try using:

^(00:0[1-9]|00:[1-5][0-9]|0[1-3]:[0-5][0-9]|04:00)$

Demo

Here is an explanation of the second regex pattern:

^(                     from the start of the string
    00:0[1-9]          match 00:01 - 00:09
    |                  or
    00:[1-5][0-9]      match 00:10 - 00:59
    |                  or
    0[1-3]:[0-5][0-9]  match 01:00 - 03:59
    |                  or
    04:00              match 04:00
)$

Upvotes: 5

Related Questions