Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

24 hour time regex for HTML 5

Tags:

html

regex

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,

like image 528
Abdul Ali Avatar asked Feb 08 '13 12:02

Abdul Ali


People also ask

How do you write time in regex?

In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›. On a 24-hour clock, if the first digit is 0 or 1, the second digit allows all 10 digits, but if the first digit is 2, the second digit must be between 0 and 3. In regex syntax, this can be expressed as ‹ 2[0-3]|[01]?[0-9] ›.

How does regular expression validate time in 12 hour format?

On a 12-hour clock, if the first digit is 0, the second digit allows all 10 digits, but if the first digit is 1, the second digit must be 0, 1, or 2. In a regular expression, we write this as ‹ 1[0-2]|0?[1-9] ›.


2 Answers

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

like image 105
radu florescu Avatar answered Sep 25 '22 08:09

radu florescu


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}" />
like image 35
pwolaq Avatar answered Sep 25 '22 08:09

pwolaq