Zipcode/Postalcode Validation

My current client has customers that are located all throughout the world, but the majority of which reside or work in the US, Canada or the UK.  We recently had a situation where a user was inputing a postal code for a Canadian residence and they did not use the expected format, which expects a space following the third character.

As an example, the postal code ‘A9F C3D’ would have been just fine, but ‘A9FC3D’ would fail the validation.

So, a bug was entered and the whole issue of postal code validation was raised.  The first option was to only perform validation on US codes, and just allow free text for any other country.  Not a bad option, since it would allow for some flexibility as new clients came on board who lived or worked in different counties.  But, it leaves the door wide open to get an invalid code and then not be able to reach a client through mailings.  The next option was to perform some validation to make sure the postal code was either a US, UK, or Canadian postal code.  Since that covers the majority of the situations, that was the decision.

There was already a reg ex on the field that did US and Canadian (with the space) validation, so it just needed to be altered a bit to accept UK codes, as well as account for no spaces or even dashes used in a Canadian code.  I did some research on UK codes and discovered there really is no rhyme or reason to them.  They could be anywhere from 6 to 12 characters long depending on the information that the code was conveying.  Wonderful.

Well, a bit more analysis and some time spent on and I finally got an acceptable pattern that would handle the majority of the cases, if not all.  I’m still not sure if I tested all of the UK possibilities just because there seems to be so much of a, well, cluster-fuck of ways to build a code.  I’ll keep my fingers crossed.  I guess I’m just a stupid American used to being able to validate with a simple d{5}-d{4}|d{5} validation.

For future reference, here’s what I ended up with:
^(d{5}-d{4}|d{5})$|([A-Za-z]d[A-Za-z][s.-]?(|-)d[A-Za-z]d)|[A-Za-z]{1,2}d{1,2}[A-Za-z]? d[A-Za-z]{2}$


On a separate note, but related, I came across a posting by Chris McKenzie where he asks for a free listing of US codes and their associated city/state info.  There have been many times when I’ve desired this info as well, so it’s good to see some options out there.  A couple options mentioned by folks in his comments are here and here, with a 1999 listing here.  Good to know for the next time I need this stuff.

Leave a Reply

Your email address will not be published.