Validate US Zip Code format with Rails

Michał Makaruk picture Michał Makaruk · Nov 21, 2011 · Viewed 18.6k times · Source

How do you validate a U.S. zip code using Rails?

I wrote something like this but it doesn't work:

validates_format_of :zip_code,
  :with => /^\d{5}(-\d{4})?$/,
  :message => "Zip code should be valid"

Answer

Michael Durrant picture Michael Durrant · Nov 21, 2011

You can also validate that it is actually a valid zip (not just the format but the zip itself) using:
http://www.webservicex.net/uszip.asmx?op=GetInfoByZIP

Try a valid zip you know, e.g. 02135 vs an invalid one like 09990 to see the difference.

I would consider combining this with:

validates_format_of :zip, :with => /^\d{5}(-\d{4})?$/, :message => "should be in the form 12345 or 12345-1234"

that it's done with validate_format_of, rather than validate_format_of_zip_code as that means it can also be used for phone numbers, etc that also fit a fixed, known, format (.e.g. U.S.).
Perhaps validate format first and give error if invalid, so handle it all within rails with standard flash message.
Then, if valid make the call to that server to validate actual zip itself.

The only downside to great server supplied validations like this is that they increase the dependency on other sites and services. So if the other site/service changes things or is unavailable, etc. there is an issue. This is another reason why doing the simpler validity check first is a great idea.

A full service solution would also check for time-out by the zip code service and if that happens, say 5 seconds and the format is ok probably best to accept value. Maybe set an 'unverified_zip' flag if possible!