61
var regex = /[A-Za-z]\d[A-Za-z] ?\d[A-Za-z]\d/;
var match = regex.exec(value);
if (match){
    if ( (value.indexOf("-") !== -1 || value.indexOf(" ") !== -1 ) && value.length() == 7 ) {
        return true;
    } else if ( (value.indexOf("-") == -1 || value.indexOf(" ") == -1 ) && value.length() == 6 ) {
        return true;
    }
} else {
        return false;
}

The regex looks for the pattern A0A 1B1. true tests:

A0A 1B1

A0A-1B1

A0A1B1

A0A1B1C << problem child

so I added a check for "-" or " " and then a check for length.

Is there a regex, or more efficient method?

1
  • 1
    If you're doing this for user input, please don't be too strict. I recently wasted time on a (FAANG) website telling me my postal code was invalid because I didn't include the space. Humans are not computers and we haven't all read the specification for postal codes.
    – user3064538
    Feb 27, 2021 at 4:06

7 Answers 7

78

User kind, postal code strict, most efficient format:

/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][ -]?\d[ABCEGHJ-NPRSTV-Z]\d$/i

Allows:

  • h2t-1b8
  • h2z 1b8
  • H2Z1B8

Disallows:

  • Z2T 1B8 (leading Z)
  • H2T 1O3 (contains O)

Leading Z,W or to contain D, F, I, O, Q or U

3
  • is 'i' at the end of regex a mistype mistake or part of the full regex? Jan 13, 2020 at 18:25
  • 2
    stackoverflow.com/questions/4967369/…
    – Dan
    Jan 13, 2020 at 18:27
  • Gives error Error: '\d' is an unrecognized escape in character string starting ""/^[ABCEGHJ-NPRSTVXY]\d" when used with str_extract from stringr() Mar 16, 2022 at 17:23
50

Add anchors to your pattern:

var regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;

^ means "start of string" and $ means "end of string". Adding these anchors will prevent the C from slipping in to the match since your pattern will now expect a whole string to consist of 6 (sometimes 7--as a space) characters. This added bonus should now alleviate you of having to subsequently check the string length.

Also, since it appears that you want to allow hyphens, you can slip that into an optional character class that includes the space you were originally using. Be sure to leave the hyphen as either the very first or very last character; otherwise, you will need to escape it (using a leading backslash) to prevent the regex engine from interpreting it as part of a character range (e.g. A-Z).

7
  • 4
    I'll jump in to say he could also use the i flag so that the explicit upper/lowercase checks aren't needed.
    – Dave
    Apr 2, 2013 at 21:25
  • 11
    That will allow invalid Canadian Postal Codes. Postal codes never start with characters that might be mistaken for numbers: I, O, Q, U, W, Z... Thus: /^[ABCEGHJKLMNPRSTVXY]\d[ -]?\d[A-Za-z]\d$/; May 26, 2014 at 16:03
  • 3
    Interesting, but I wonder: If postal codes always start with a letter, why would one confuse any of the above-mentioned letters with numbers? And what number would W be confused with? I'm sure those are questions for the postal service :)
    – Kenneth K.
    May 27, 2014 at 12:09
  • 2
    /^[ABCEGHJ-NPRSTVXY][0-9][ABCEGHJ-NPRSTV-Z] [0-9][ABCEGHJ-NPRSTV-Z][0-9]$/ is a stricter regex Oct 24, 2017 at 14:24
  • 1
    a postal code can contain W or Z, but not at the first position because the first letter represent one of the 18 postal district. (one by province, but 5 in Ontario and 3 in Quebec). as you can see here : https://en.wikipedia.org/wiki... Dec 21, 2018 at 13:44
29

This one handles us and ca codes.

function postalFilter (postalCode) {

    if (! postalCode) {
        return null;
    }

    postalCode = postalCode.toString().trim();

    var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
    var ca = new RegExp(/([ABCEGHJKLMNPRSTVXY]\d)([ABCEGHJKLMNPRSTVWXYZ]\d){2}/i);

    if (us.test(postalCode.toString())) {
        return postalCode;
    }

    if (ca.test(postalCode.toString().replace(/\W+/g, ''))) {
        return postalCode;
    }
    return null;
}

// these 5 return null
console.log(postalFilter('1a1 a1a'));
console.log(postalFilter('F1A AiA'));
console.log(postalFilter('A12345-6789'));
console.log(postalFilter('W1a1a1')); // no "w"
console.log(postalFilter('Z1a1a1')); // ... or "z" allowed in first position!

// these return canada postal less space
console.log(postalFilter('a1a 1a1'));
console.log(postalFilter('H0H 0H0'));

// these return unaltered
console.log(postalFilter('H0H0H0'));
console.log(postalFilter('a1a1a1'));
console.log(postalFilter('12345'));
console.log(postalFilter('12345-6789'));
console.log(postalFilter('123456789'));

// strip spaces
console.log(postalFilter(' 12345 '));
2
  • 3
    This answer has a cleaner and more accurate regex than the currently accepted answer, because Canada postal codes always omit the letters D, F, I, O, Q and U. /([ABCEGHJKLMNPRSTVWXYZ]\d){3}/i One condition missing, though, is that the first letter cannot be W or Z. en.wikipedia.org/wiki/… Oct 2, 2015 at 10:29
  • @RobertPenner is correct. I corrected the regular expression for Canada codes. I'd bet a dollar there is a nicer way to do it, though.
    – lysdexia
    Jan 22, 2016 at 20:48
18

You have a problem with the regex StatsCan has posted the rules for what is a valid Canadian postal code:

The postal code is a six-character code defined and maintained by Canada Post Corporation (CPC) for the purpose of sorting and delivering mail. The characters are arranged in the form ‘ANA NAN’, where ‘A’ represents an alphabetic character and ‘N’ represents a numeric character (e.g., K1A 0T6). The postal code uses 18 alphabetic characters and 10 numeric characters. Postal codes do not include the letters D, F, I, O, Q or U, and the first position also does not make use of the letters W or Z.

The regex should be if you wanted it strict.

/^[ABCEGHJ-NPRSTVXY][0-9][ABCEGHJ-NPRSTV-Z] [0-9][ABCEGHJ-NPRSTV-Z][0-9]$/

Also \d means number not necessarily 0-9 there may be the one errant browser that treats it as any number in unicode space which would likely cause issues for you downstream.

from: https://trajano.net/2017/05/canadian-postal-code-validation/

0

This is a function that will do everything for you in one shot. Accepts AAA BBB and AAABBB with or without space.

function go_postal(){
        let postal = $("#postal").val();
        var regex = /^[A-Za-z]\d[A-Za-z][ -]?\d[A-Za-z]\d$/;
        var pr = regex .test(postal);
        if(pr === true){
            //all good          
        } else {
            // not so much
        }
    }
-1
function postalFilter (postalCode, type) {

    if (!postalCode) {
        return null;
    }

    postalCode = postalCode.toString().trim();

    var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
   // var ca  = new RegExp(/^((?!.*[DFIOQU])[A-VXY][0-9][A-Z])|(?!.*[DFIOQU])[A-VXY][0-9][A-Z]\ ?[0-9][A-Z][0-9]$/i);
    var ca = new RegExp(/^[ABCEGHJKLMNPRSTVXY]\d[ABCEGHJKLMNPRSTVWXYZ]( )?\d[ABCEGHJKLMNPRSTVWXYZ]\d$/i);

    if(type == "us"){
        if (us.test(postalCode.toString())) {
            console.log(postalCode);
            return postalCode;
        }
    }

    if(type == "ca")
    {
        if (ca.test(postalCode.toString())) {
            console.log(postalCode);
            return postalCode;
        }
    }

    return null;
}
-1
regex = new RegExp(/^[ABCEGHJ-NPRSTVXY]\d[ABCEGHJ-NPRSTV-Z][-]?\d[ABCEGHJ-NPRSTV-Z]\d$/i);
if(regex.test(value))
    return true;
else
    return false;

This is a shorter version of the original problem, where value is any text value. Furthermore, there is no need to test for value length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.