Canadian Postal Code Regex for JavaScript
/^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/iWhat this pattern does
This page provides a comprehensive, battle-tested regular expression for matching canadian postal code, 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
// Canadian Postal Code
// ReDoS-safe | RegexVault — Localization > Postal Codes
const canadianPostalCodeRegex = /^([ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ])\s?([0-9][ABCEGHJKLMNPRSTVWXYZ][0-9])$/i;
function validateCanadianPostalCode(input: string): boolean {
return canadianPostalCodeRegex.test(input);
}
// Example
console.log(validateCanadianPostalCode("K1A 0B1")); // trueTest Cases
Matches (Valid) | Rejects (Invalid) |
|---|---|
K1A 0B1 | K1A 0B |
M5V 3L9 | K1A0B12 |
V6B 1G4 | Z1A 0B1 |
T2P 3C3 | K1A OB1 |
K1A0B1 | D1A 0B1 |
When to use this pattern
This pattern is drawn from the Localization > Postal Codes 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
The FSA (Forward Sortation Area, first 3 characters) uniquely identifies a delivery area. The LDU (Local Delivery Unit, last 3) narrows to a block. The boundary between FSA and LDU is always a space.
Technical Notes
First letter identifies the province. Invalid first letters: D, F, I, O, Q, U, W (excluded because they resemble digits in some fonts or were reserved). The letter D and I are also excluded from all positions for readability.
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