20

Wanted to Inquire about the possible Regex expression for 24-hour time format in HTML 5 (HH:MM) .

if possible, kindly tell the regex that can be used in the Pattern attribute of HTML 5

The time is expected to be in 24-hour format (HH not more than 23).

Kind regards,

Abdul Ali
  • 1,905
  • 8
  • 28
  • 50

4 Answers4

27

I think this is a possible approach :

<input type="text" pattern="([01]?[0-9]|2[0-3]):[0-5][0-9]" id="24h"/>
<input type="text" pattern="([01]?[0-9]{1}|2[0-3]{1}):[0-5]{1}[0-9]{1}" id="24h"/>

http://www.mkyong.com/regular-expressions/how-to-validate-time-in-24-hours-format-with-regular-expression/

([01]?[0-9]|2[0-3]):[0-5][0-9]

Check out this jsfiddle : example

radu florescu
  • 4,315
  • 10
  • 60
  • 92
20

Here is the code:

<input type="text" pattern="[0-2]{1}[0-9]{1}:[0-5]{1}[0-9]{1}" />

it does allow invalid hour values: 24,25,26,27,28,29, if you want to be extra correct you can do it that way:

<input type="text" pattern="([0-1]{1}[0-9]{1}|20|21|22|23):[0-5]{1}[0-9]{1}" />
pwolaq
  • 6,343
  • 19
  • 45
  • 1
    If talking about time, for sure I want the Extra Correct way, Thank you, it worked like a charm! – Daniel Jun 30 '15 at 14:42
3

If you want to force to have the format HH:MM (e.g. 00:00, 23:59)

Then, you could use something like this:

/^([01]\d|20|21|22|23):[0-5]\d$/
Eduardo Vazquez
  • 2,454
  • 1
  • 12
  • 8
1

A bit shorter regex:

(?:[01]|2(?![4-9])){1}\d{1}:[0-5]{1}\d{1}

So in complete:

<input type="text" pattern="(?:[01]|2(?![4-9])){1}\d{1}:[0-5]{1}\d{1}" />

In the first non-capturing group ("(?:)") we match exactly one digit, either 0, 1 or 2 not followed by 4-9 (negative lookahead "(?!)"). Then me match one more digit, since it could be any of 0-9 we can go with \d shortcut. Then we match separator ":". Then one digit between 0-5 and one more between 0-9 (again with "\d"). If for some reason you need to match 24 hours as well (sometimes you do), then just adjust negative lookahead, e. g. "(?![5-9])".

SKS
  • 11
  • 1