12-Hour Time (H:MM AM/PM) Regex for JavaScript
/^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/iWhat this pattern does
This page provides a well-structured, multi-part regular expression for matching 12-hour time (h:mm am/pm), ported and verified for JavaScript. A rigorously tested regex reduces debugging time and protects your application from edge-case failures. The snippet below is ready to drop into your JavaScript project — whether you're validating in an Express middleware, a Next.js API route, or a client-side form.
Javascript Implementation
// 12-Hour Time (H:MM AM/PM)
// ReDoS-safe | RegexVault — Localization > Time Formats
const 12hourTimeHmmAmpmRegex = /^(1[0-2]|0?[1-9]):([0-5][0-9])(?::([0-5][0-9]))?\s?(AM|PM|am|pm|Am|Pm)$/i;
function validate12hourTimeHmmAmpm(input: string): boolean {
return 12hourTimeHmmAmpmRegex.test(input);
}
// Example
console.log(validate12hourTimeHmmAmpm("12:30 PM")); // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
12:30 PM | 13:00 PM |
1:05 AM | 0:30 AM |
11:59:59 PM | 12:60 PM |
12:00 AM | 12:30 |
9:30am | 12:30 pm extra |
12:00PM | — |
When to use this pattern
This pattern is drawn from the Localization > Time Formats category and carries a ReDoS-safe certification. That matters for JavaScript developers because especially critical in long-running Node.js event loops where a ReDoS vulnerability can block the entire process. RegexVault audits patterns against known backtracking attack vectors, ensuring you have the necessary context before using this regex in a high-stakes production environment.
Common Pitfalls
12:00 AM (midnight) and 12:00 PM (noon) confuse even native English speakers. Consider rejecting 12-hour format for any time-critical input and requiring 24-hour instead.
Technical Notes
12:00 AM = midnight, 12:00 PM = noon — the most commonly confused values. 12-hour format is standard in US, UK, Australia, and parts of Asia. Many others use 24-hour exclusively.
Have a pattern that belongs in the vault?
Submit it for review — community-verified patterns get credited to your GitHub handle. Free submissions join the queue. Priority review available for $15.
Submit a Pattern