Validate a Canadian postal code in JavaScript
Intermediate · 3 min read
A Canadian postal code alternates letters and digits: K1A 0B1, M5V 3L9. Online shops, tax forms and sign-up pages that serve Canada check this field before accepting an address. The shape is easy to describe. What makes this exercise interesting is that some letters are never used, and two more are banned only in the first position.
In this tutorial you will turn those rules into character classes, step by step, and finish with a function that tidies the input into the standard A1A 1A1 form. You need to know /.../.test(), ^, $ and \d. Ranges inside classes are explained as we go.
The rules
- The shape is letter, digit, letter, space, digit, letter, digit:
A1A 1A1. - The letters
D,F,I,O,QandUare never used anywhere. They are too easy to confuse with0,1and each other when handwritten or read by a machine. WandZare also not used as the first letter. They are fine in the other positions.
Ranges inside a class
In a character class, A-Z is every letter from A to Z. You can also write smaller ranges and single letters side by side. [ABCJ-N] means A, B, C, or anything from J to N:
console.log(/^[ABCJ-N]$/.test('L')); // true: L is between J and N
console.log(/^[ABCJ-N]$/.test('D')); // false
That lets us write "every letter except a few" in a short space.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
14 Validate a Canadian postal code
fairCheck a Canadian postal code: letter, digit, letter, space, digit, letter, digit. Some letters are never used.
Stuck? Three hints, smallest first
- 1. The alternating pattern is
A1A 1A1. - 2.
D,F,I,O,QandUare never used, because they look like digits or other letters. - 3.
WandZare also excluded from the first position only.
Step 1: the shape, without the letter rules
Start with the alternating shape and the space in the middle:
const SHAPE = /^[A-Z]\d[A-Z] \d[A-Z]\d$/;
console.log(SHAPE.test('K1A 0B1')); // true
console.log(SHAPE.test('1A1 A1A')); // false: wrong order
console.log(SHAPE.test('D1A 0B1')); // true, but D is never used
The last line shows what is missing.
Step 2: the letters allowed everywhere
Take the alphabet and remove D, F, I, O, Q and U. What's left can be grouped into runs:
A B C E G H J K L M N P R S T V W X Y Z
ABC E GH J-N P RST V-Z
Joined up, that is [ABCEGHJ-NPRSTV-Z]. This class is used for the second and third letters:
const LATER = /^[ABCEGHJ-NPRSTV-Z]$/;
console.log(LATER.test('K')); // true
console.log(LATER.test('W')); // true
console.log(LATER.test('O')); // false
console.log(LATER.test('U')); // false
Step 3: the first letter
The first letter also can't be W or Z. Change the end of the class from V-Z (V, W, X, Y, Z) to VXY, which keeps V, X and Y:
const FIRST = /^[ABCEGHJ-NPRSTVXY]$/;
console.log(FIRST.test('K')); // true
console.log(FIRST.test('W')); // false
console.log(FIRST.test('Z')); // false
Step 4: the full pattern
Put the two classes in their places. Use [ -]? in the middle so a missing space or a dash is fine too, and the i flag so lower case is accepted:
const CA_POSTCODE = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
const isCaPostal = (value) => typeof value === 'string' && CA_POSTCODE.test(value.trim());
console.log(isCaPostal('K1A 0B1')); // true
console.log(isCaPostal('k1a0b1')); // true
console.log(isCaPostal('K1A-0B1')); // true
console.log(isCaPostal('W1A 0B1')); // false: W first
console.log(isCaPostal('K1W 0B1')); // true: W third is fine
console.log(isCaPostal('D1A 0B1')); // false
The W lines are the ones to watch. They prove the two different classes are doing their jobs.
Step 5: tidy the input
Store and show postal codes in capitals with one space in the middle. Remove spaces and dashes, then put the space back after the third character:
const CA_POSTCODE = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
const isCaPostal = (value) => typeof value === 'string' && CA_POSTCODE.test(value.trim());
const normalise = (value) => {
if (!isCaPostal(value)) return null;
const bare = value.trim().toUpperCase().replace(/[\s-]/g, '');
return `${bare.slice(0, 3)} ${bare.slice(3)}`;
};
console.log(normalise('k1a0b1')); // 'K1A 0B1'
console.log(normalise('m5v-3l9')); // 'M5V 3L9'
console.log(normalise('D1A 0B1')); // null
The full solution
The panel checks real codes, including H0H 0H0 (the postal code Canada Post uses for letters to Santa), and a bad example for each banned letter. Press Run and read down the "bad" rows.
/* Excluded letters:
everywhere D F I O Q U (too easily confused with 0, 1 and each other)
first position also W and Z
The character classes below encode exactly that. */
const CA_POSTCODE = /^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i;
const isCaPostal = (value) => typeof value === 'string' && CA_POSTCODE.test(value.trim());
const normalise = (value) => {
if (!isCaPostal(value)) return null;
const bare = value.trim().toUpperCase().replace(/[\s-]/g, '');
return `${bare.slice(0, 3)} ${bare.slice(3)}`;
};
const real = ['K1A 0B1', 'M5V 3L9', 'H0H 0H0', 'V6B 4Y8', 'T2P 2M5'];
const bad = ['D1A 0B1', 'F1A 0B1', 'I1A 0B1', 'O1A 0B1', 'Q1A 0B1', 'U1A 0B1',
'W1A 0B1', 'Z1A 0B1', '1A1 A1A', 'K1A 0B', 'K1A0B12', '', '12345'];
for (const p of real) console.log('real ', p.padEnd(10), isCaPostal(p), '->', JSON.stringify(normalise(p)));
for (const p of bad) console.log('bad ', JSON.stringify(p).padEnd(10), isCaPostal(p));
console.log('no space:', isCaPostal('K1A0B1'), '-> normalised', JSON.stringify(normalise('K1A0B1')));
console.log('a dash :', isCaPostal('K1A-0B1'), '-> normalised', JSON.stringify(normalise('K1A-0B1')));
console.log("H0H 0H0 is Santa Claus's real postal code, and it validates.");
Output
23 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 23 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('every real example passes', real.every(isCaPostal), true);
test('the classic K1A 0B1', isCaPostal('K1A 0B1'), true);
test('a Toronto code', isCaPostal('M5V 3L9'), true);
test('H0H 0H0 is genuinely valid', isCaPostal('H0H 0H0'), true);
test('the space may be missing', isCaPostal('K1A0B1'), true);
test('a dash is tolerated', isCaPostal('K1A-0B1'), true);
test('lower case is accepted', isCaPostal('k1a 0b1'), true);
test('D is never used', isCaPostal('D1A 0B1'), false);
test('nor F', isCaPostal('F1A 0B1'), false);
test('nor I', isCaPostal('I1A 0B1'), false);
test('nor O', isCaPostal('O1A 0B1'), false);
test('nor Q', isCaPostal('Q1A 0B1'), false);
test('nor U', isCaPostal('U1A 0B1'), false);
test('W is excluded from the first position', isCaPostal('W1A 0B1'), false);
test('but allowed in the third', isCaPostal('K1W 0B1'), true);
test('Z is excluded from the first position', isCaPostal('Z1A 0B1'), false);
test('and allowed in the third', isCaPostal('K1Z 0B1'), true);
test('the digit and letter order matters', isCaPostal('1A1 A1A'), false);
test('too short is refused', isCaPostal('K1A 0B'), false);
test('too long is refused', isCaPostal('K1A0B12'), false);
test('an empty string is refused', isCaPostal(''), false);
test('normalising gives one space in the middle', normalise('k1a0b1'), 'K1A 0B1');
test('and an invalid code gives null', normalise('D1A 0B1'), null);
The excluded letters are the whole point, and they are excluded for a good reason: D, F, I, O, Q and U are too easily confused with 0, 1 and each other when handwritten or read by a scanner. W and Z are additionally excluded from the first position only, which is why the two character classes in the pattern differ — [ABCEGHJ-NPRSTVXY] for the first, [ABCEGHJ-NPRSTV-Z] for the others. The assertions check K1W 0B1 passes while W1A 0B1 does not, so that distinction cannot silently collapse.
The ranges do the compressing: J-N is J, K, L, M, N, and V-Z is V, W, X, Y, Z. Writing them out letter by letter would be clearer to read but much longer, which is the usual regex trade.
Common mistakes
- Using
[A-Z]for every letter. It lets in D, F, I, O, Q and U, which never appear in a real code. - Banning W and Z everywhere. They are only banned in the first position.
K1W 0B1is valid. - Writing the dash in the middle of a class. In
[ -]the dash is last, so it means a real dash. Between two characters it would make a range.
Try it yourself
- Write
province(code)that returns'Ontario'when the first letter is K, L, M, N or P. - Make the check strict: require exactly one space, no dash.
- Write out
[ABCEGHJ-NPRSTV-Z]as single letters and count them. You should get 20.