Below RegEx should work. Demo script
var regex = /^([0]\d|[1][0-2]):([0-5]\d)\s?(?:AM|PM)$/i; /* The below lines are just for demo testing purpose */ var timeStr = ["13:59am","11:59AM","09:69PM", "09:24pm", "09:99pm", "15:23bm", "09:23 AM", "14:74 PM"]; for (i=0; i<timeStr.length; i++) console.log("Time String: "+timeStr[i]+ " Result: " +regex.test(timeStr[i]));
RegEx Explanation:
([0]\d|[1][0-2])
- For the hours. Either 0
, followed by any digit (or) 1
, followed by any single digit between 0-2
(i.e. 0 or 1 or 2). This is done so that the clock value, for example 13 or 14, etc., is considered invalid (since we use time in AM / PM format, the clock value should be no more than 12).
([0-5]\d)
- for minutes. Any digit between 0-5
, and then another digit between 0-9
. This is to ensure that in minutes, such as 64, 79, etc. They were considered invalid.
\s?
- 0 or 1 space
(?:AM|PM)$/i
- case insensitive AM or PM (that is, am | pm | Am | Pm | aM | pM | AM | PM
)
Console exit:
Time String: 13:59 am Result: false
Time String: 11:59 AM Result: true
Time String: 09:69 PM Result: false
Time String: 09:24 pm Result: true
Time String: 09:99 pm Result: false
Time String: 15: 23bm Result: false
Time String: 09:23 AM Result: true
Time String: 14:74 PM Result: false
Harry source share