tags:

views:

729

answers:

4

Hi,

I need to validate Canada postal code (for example:M4B 1C7) using C# regular expressions.

Please help.

Thanks.

+1  A: 

I suggest the following:

bool FoundMatch = false;
try {
    FoundMatch = Regex.IsMatch(SubjectString, "\\A[ABCEGHJKLMNPRSTVXY]\\d[A-Z] ?\\d[A-Z]\\d\\z");
} catch (ArgumentException ex) {
    // Syntax error in the regular expression
}
Templar
I've modified my answer to exclude invalid letters in the first character, as per http://www.infinitegravity.ca/postalcodeformat.htm.
Templar
f you don't want to have to do two slashes for every slash, use an @ string literal as in `@"\A[ABCEGHJKLMNPRSTVXY]\d[A-Z] ?\d[A-Z]\d\z"`.
cdmckay
+1  A: 

Something like this:

^[A-Z]\d[A-Z] \d[A-Z]\d$
Colin Mackay
Not all letters are valid in the postal codes.
Tilendor
+13  A: 
[ABCEFGHJKLMNPRSTVXY][0-9][ABCEFGHJKLMNPRSTVWXYZ][0-9][ABCEFGHJKLMNPRSTVWXYZ][0-9]

Canadian postal codes can't have certain letters. ( D, I, O, etc.) :D

source

EDIT: oh, and if you wanted a space in the middle you can use

[ABCEFGHJKLMNPRSTVXY][0-9][ABCEFGHJKLMNPRSTVWXYZ] [\s]  [0-9][ABCEFGHJKLMNPRSTVWXYZ][0-9]

\s will match any whitespace, newline and tab included. If you don't want those you could either use ^ to remove newlines and tabs or look up the ascii for the space character.

CrazyJugglerDrummer
+1 for "Canadian postal codes can't have certain letters". You might want to also add that the leading letter is more restricted, then the second and third.
Richard C. McGuire
thanks a ton for answer...this works fine for codes like M4B1E8 ...but it wont work for M4B 1E8. Canada postal could have space after 3 characters..reference here:http://www.mongabay.com/igapo/toronto_zip_codes.htm
Jimmy
Ideally, you should ignore whitespace on input and normalise the data to a canonical format for storage. That way, people can enter postal codes with or without spaces, and it won't matter. You can format them for output purposes if needed.
Rob
There shouldn't be an F in the first sequence, you can check here: http://www.infinitegravity.ca/postalcodeformat.htm to verify
Tilendor
If you want the space to be optional, put a question mark after it.
GalacticCowboy
+1  A: 

Validating the format of a postal code without validating its meaning isn't worth it, since typos can still result in a valid postal code for the wrong address. You want to validate the code against the address database. See http://www.canadapost.ca/cpo/mc/business/productsservices/atoz/postalcodeproducts.jsf

joe snyder