Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canadian postal code validation

Tags:

c#

.net

regex

I need to validate a Canadian postal code (for example, M4B 1C7) using C# (.NET) regular expressions.

like image 893
Jimmy Avatar asked Jul 17 '09 23:07

Jimmy


People also ask

What is the correct format for a Canadian postal code?

The postal code is a six-character uniformly structured, alphanumeric code in the form “ANA NAN” where “A” is an alphabetic character and “N” is a numeric character. Two segments make up a postal code: Forward Sortation Area (FSA) and Local Delivery Unit (LDU).

Why is my Canadian postal code invalid?

You will see this error when the zip or postal code of your address does not match your purchasing card. Simply review what the postal or zip code of your purchasing card is, and re-enter the correct information to proceed.


2 Answers

Canadian postal codes can't contain the letters D, F, I, O, Q, or U, and cannot start with W or Z:

[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]

If you want an optional space in the middle:

[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ] ?[0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]
like image 164
Gordon Gustafson Avatar answered Oct 18 '22 02:10

Gordon Gustafson


Here are the rules http://en.wikipedia.org/wiki/Postal_code#Reserved_characters

ABCEGHJKLMNPRSTVXY <-- letter used 
DFIOQU <-- letters not used because it mixes up the reader
WZ     <-- letters used but not in the first letter
With that in mind the following in the proper regex

@[ABCEGHJKLMNPRSTVXY][0-9][ABCEGHJKLMNPRSTVWXYZ][\s][0-9][ABCEGHJKLMNPRSTVWXYZ][0-9]
like image 5
user3111634 Avatar answered Oct 18 '22 02:10

user3111634