24 Hour Time Regex For HTML 5
Solution 1:
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"/>
([01]?[0-9]|2[0-3]):[0-5][0-9]
Check out this jsfiddle : example
Solution 2:
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}" />
Solution 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:
/^([0-1]\d|20|21|22|23):[0-5]\d$/
Solution 4:
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])".
Post a Comment for "24 Hour Time Regex For HTML 5"