-2

I am trying to impose a regex pattern on a text input where an user can only insert a time between 9:00 and 17:00. I have tried the following which validates any time format but I am not sure how to get certain intervals restrictions.

This is what I tried:

([0-1]{1}[0-9]{1}):[0-5]{1}[0-9]{1}

What would be the ideal regex pattern to verify that the time inserted in a text input matches the time between 9:00 and 17:00 ?

Avocado
  • 93
  • 8

1 Answers1

1

The trick is to define ORed ranges of numbers:

Regex: ^((0?9|1[0-6]):[0-5][0-9]|17:00)$

Tests:

  • 8:59 ==> false
  • 9:00 ==> true
  • 9:01 ==> true
  • 08:59 ==> false
  • 09:00 ==> true
  • 09:01 ==> true
  • 10:00 ==> true
  • 10:01 ==> true
  • 10:59 ==> true
  • 10:60 ==> false
  • 16:59 ==> true
  • 17:00 ==> true
  • 17:01 ==> false

Explanation of regex:

  • ^...$ - anchor at beginning and end
  • (...|17:00) - expect pattern A (explained below), or 17:00 (special case)
  • (...):[0-5][0-9] - pattern A is pattern B, followed by :, 0-5, followed by 0-9 for minutes 00 to 59
  • (0?9|1[0-6]) - pattern B is ORed hour:
  • 0?9 - optional 0, followed by 9 (for optional zero padding)
  • 1[0-6] - or a 1, followed by 0-6 (for hour 10 to 16
Peter Thoeny
  • 7,379
  • 1
  • 10
  • 20