Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One Regular Expression to validate US and Canada ZIP / Postal Code

Tags:

regex

I am developing a stationery program. Customers have choice to pick their region either US or Canada. When they enter address they have to enter ZIP/Postal code. I am trying to validate field but I cannot use reg exp either for US or Canada. I require a regular expression that validates for both country zip code.

like image 634
user3149507 Avatar asked Mar 20 '14 21:03

user3149507


2 Answers

Not knowing what language you're using, I will not use any abbreviations for character classes:

^[0-9]{5}$|^[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9]$

Depending on your language, you might be able to abbreviate this to

^([0-9]{5}|[A-Z][0-9][A-Z] ?[0-9][A-Z][0-9])$

or

^(\d{5}|[A-Z]\d[A-Z] ?\d[A-Z]\d)$

To support ZIP+4:

^(\d{5}(-\d{4})?|[A-Z]\d[A-Z] ?\d[A-Z]\d)$

And if you want to get really picky about your Canada codes:

^(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$
like image 200
dg99 Avatar answered Sep 30 '22 18:09

dg99


Furthering the answer above you could add (?i) to the beginning of the regex to make is case insensitive. So it would look like this:

^(?i)(\d{5}(-\d{4})?|[A-CEGHJ-NPRSTVXY]\d[A-CEGHJ-NPRSTV-Z] ?\d[A-CEGHJ-NPRSTV-Z]\d)$
like image 26
Kurt LP Avatar answered Sep 30 '22 16:09

Kurt LP