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]$/
Share:
11,382
A. MO
Author by

A. MO

Updated on June 09, 2022

Comments

  • A. MO
    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
    A. MO about 8 years
    I mean I need AM and PM Should not be case sensitive
  • RobG
    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
    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
    A. MO about 8 years
    Thanks Guys It Worked
  • arximughal
    arximughal almost 6 years
    Works like a charm <3
  • axmrnv
    axmrnv over 5 years
    Remove ? after 0 to require leading zero in hour.
  • Robert Penner
    Robert Penner over 4 years
    Note that this answer only works if the minutes are a multiple of 5, which may not be immediately obvious in the question.
  • Sean Hetzel
    Sean Hetzel over 3 years
    The ^ at the beginning is very important because it prevents 17:30 PM from getting mistaken as 7:30 PM if the user inputs 24 hour time format by mistake.
  • coolk
    coolk over 2 years
    this is NOT the right answer as per comment by Robert