Grayscale profile picture

Patrique Ouimet

Senior Product Engineer

Canadian Postal Code Regex in JavaScript

Fri, Oct 25, 2019 12:55 PM

A simple javascript regex test to verify if a string is a valid postal code in Canada.

function testCanadianPostalCode(postalCode)
{
    const postalCodeRegex = new RegExp(/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVXY][ -]?\d[ABCEGHJKLMNPRSTVXY]\d$/i);

    return postalCodeRegex.test(postalCode);
}

testCanadianPostalCode('A1A 1A1'); // true
testCanadianPostalCode('A1A 111'); // false
testCanadianPostalCode('A1Q 1A1'); // false
testCanadianPostalCode('A1A1A1');  // true
testCanadianPostalCode('A1A-1A1'); // true