You are hereBlogs / alif's blog / Canada Postal Code & US Zip Code Regex

Canada Postal Code & US Zip Code Regex


By alif - Posted on 08 July 2010

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
Tags

Thank you for this script. I just saved few hours!

nice regex abdullah :)

thanks

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

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.