Parsing ZIP Codes
As with all advice, feel free to drop by and suggest a better library / module! REL makes no claims that these are the best modules, just a few that seem to do the job from some quick searching.
What no one should say ever:
I know, I'll just parse this zip code with a regex real quick, it's just 6 digits...
Put the editor down. Step away from the console. Show me your license and registration.
ZIP codes often baffle people outside of the US. Despite the US Postal Service deciding on their Zone Improvement Plan, the five digit common form has been around since the 1960s, but almost nowhere else. That hasn’t stopped enterprising US devs from adding ZIP code fields in place of the Postal Codes often used elsewhere. Take a look at this code for the BBC Bridge House: M50 2BH or Buckingham Palace: SW1A 1AA. When I lived in Hong Kong, which uses no codes (ZIP, Postal, or otherwise), form validation often made ordering things online a little more interesting than it should be, though thankfully entries like 0000 often worked.
Also, think hard about your validation strategy before entirely ignoring the non-US Postal Code case. It may be you that suddenly gets the privilege of extending the ecom service as it’s taking off to handle international addressing.
A common case for validating a ZIP code is as part of a delivery / mailing address. Let’s start with some gotchas:
- ZIP codes have had 4 digit extensions since 1983, you can see how well that’s going. We all did our civic duty in improving OCR to read addresses.
- The hyphen is optional, except when it’s required.
- Storing the ZIP code as an ordinary number will often lose the initial 0 (when present)
- The barcode may add on to the ZIP+4 with an extra 10th or 11th digit if that was the datasource
- ZIP codes can change the meaning of the non-ZIP parts of the address in the case of individuals (such as ZIPs 88888 or 20252), complicating valid address matching
While it may be useful to validate extant data (such as US addresses stored in a db), for validating mail / parcel delivery, you’ll often get a better result by validating the postal address rather than throwing a regex on a ZIP code. For commercial cases, there are online and offline methods of doing this, depending on purchasing priorities, or free / low cost versions for non-commercial cases.
- Postal APIs: too many to list.
- Global Postal APIs: more expensive, but they’re around
- Offline / roll your own API: Offline datasets are available from the USPS and others.
Drop by twitch / discord if you have a favorite non-regex version you’d like to mention.