Weblog of Alif

Exploring the Web: An Apple a day

Canada Postal Code & US Zip Code Regex

July 8, 2010 -- alif

I decided to write a simple Canadian Postal Code and US Zip Code Regex. There are already good ones on the web, like here for example. But, I decided to write my own to make it slightly more accurate.

Canadian Postal Code Regex

Canada's Postal Code format is 'A1A 1X1' or 'a1a1x1'. Its made up of two parts. Forward Sortation Area (FSA) and Local Delivery Unit (LDU). Read more on wikipedia. The letters D, F, I, O, Q, or U are not used on postal Code. So, the Postal Code would be roughly (note that when applying the regex, the case-insensitive (i) modifier should be used):



US Zip Code Regex

US Zip Code format seems to be straightforward. It needs to have 5 digits followed by an optional 4 digit. So, the Zip Code would be roughly:



Merging US & Canadian Postal Code

Now, both Postal Code and Zip Code could be merged, using an OR (|) operator, into one regex:




Javascript Example:

Below is a basic Javascript example:
Enter a Sample Postal/Zip Code:

AttachmentSize
postalzipcode.html1.65 KB

Comments

Submitted by Anonymous (not verified) on

Regex is not correct for both Forward Sortation Area (FSA) and Local Delivery Unit (LDU). It only work on capital letters.

Submitted by alif on

Hello, if you apply the case-insensitive modifier (i), then the regex would become case insensitive. If you read my blog I mentioned the following thing: "note that when applying the regex, the case-insensitive (i) modifier should be used".

Most regex library supports case insensitive modifier. If you are using a language where it doesn't support the case-insensitive modifier, then you can manually add another (OR |) and repeat the whole regex with its lower-case.

Submitted by Dan (not verified) on

Nice one. I prefer to keep USA and Canada as separate instead of combining them.

Add new comment