How to validate 12-Hour Time with regex (regular Expression)
11,382
Solution 1
try this :
(((0[1-9])|(1[0-2])):([0-5])([0-9])\s(A|P)M)
test regex here
try this for case sensitive AM|PM|am|pm : `
(((0[1-9])|(1[0-2])):([0-5])(0|5)\s(A|P|a|p)(M|m))
`
Solution 2
Try ,
^(1[0-2]|0?[1-9]):[0-5][0-9] (AM|PM)$
You may test here
Solution 3
This will work for both pm/am and PM/AM and prefixed with or without 0(Zero)
/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/
Author by
A. MO
Updated on June 09, 2022Comments
-
A. MO almost 2 years
I want to validate a 12-Hours time format like (01:05 PM) in PHP, Javascript and HTML.
I tried this:
((([1-9])|(1[0-2])):([0-5])(0|5)\s(A|P)M)
But I don't know why it doesn't work.
-
A. MO about 8 yearsI mean I need AM and PM Should not be case sensitive
-
RobG about 8 years@A.MO—because it needs to be 01:20 or 01:25 (the last group should be
([0-5][0-9])
. ;-) -
bob about 8 years(((0[1-9])|(1[0-2])):([0-5])(0|5)\s(A|P|a|p)(M|m)) : try this
-
A. MO about 8 yearsThanks Guys It Worked
-
arximughal almost 6 yearsWorks like a charm <3
-
axmrnv over 5 yearsRemove
?
after0
to require leading zero in hour. -
Robert Penner over 4 yearsNote that this answer only works if the minutes are a multiple of 5, which may not be immediately obvious in the question.
-
Sean Hetzel over 3 yearsThe
^
at the beginning is very important because it prevents17:30 PM
from getting mistaken as7:30 PM
if the user inputs 24 hour time format by mistake. -
coolk over 2 yearsthis is NOT the right answer as per comment by Robert