We've released a new gem for all your postal code formatting and validation needs. GoingPostal will validate and correctly format postal codes from the UK, US, Canada, Australia, New Zealand, and South Africa, and can be used as either a model mixin or as a namespaced collection of static methods.
Picture the scene...
Imagine the following conversation in your asynchronous group communications tool of choice:
<creepily-moustached-pm> We need this postcode field to be editable, right now!
<humble-ruby-dev> Sure thing!
The Humble Ruby Dev thinks "I'll have this done in 5 minutes..." He starts hacking away and gets as far as:
OK, what now? That 5-minute-feature just became a lot more work. With the WLD platform we operate in 7 countries, and none of them agree on a postcode format, so this isn't your standard "google for a quick regular expression" validation.
We had some code for attempting to take any old string and convert it to a formatted postcode (so we can be permissive with the input when looking up latitude and longitude from a postcode) so that was the first stop. It was good start but validation was what we were really after, so it was off to Wikipedia to figure out postcode formats from around the world.
Did you know Santa's postcode is H0H 0H0?
Armed with this new found knowledge and more, I opened up my editor and started coding. With a number of Ruby projects, ranging from Rails and Sinatra apps, to quick and dirty scripts, something flexible would be the most useful. Simple and flexible usually go together, so a short while later a module with a handful of methods like
format_us_postcode was born.
This got tidied up a bit with
format_postcode entry points, taking a
country_code parameter to switch the validation and formatting rules, and a little trick to make this parameter optional when the module is mixed in to a class with a
country_code method. A great naming suggestion from one of the globaldev team and we have GoingPostal.
You can install from RubyGems (
gem install going_postal) and the code is up on GitHub. It currently supports UK, US, Canadian, Australian, New Zealand, and South African postal codes (plus rules to say no postcode is valid in Ireland, as they don't use them), and we'd love to accept contributions to add rules for more countries.