egyamado egyamado - 2 years ago 198
Ruby Question

What is good way to validates Canadian Postal Code in Rails?

I'm working on Rails 4 app, and need to validates against Canadian Post Code such as "B1C 2B3" as part of user address.

I have found this gem but i think it's over kill just for validation.

Is there another way to write validation for Post Code?

Answer Source

I found on debuggex (a great regex testing site) that the canadian postal code regex is

[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1}[ -]?\d{1}[A-Z]{1}\d{1}

To check a string against that pattern, do the following for your validation:

canadian_postal_code = /\A[ABCEGHJKLMNPRSTVXY]{1}\\d{1}[A-Z]{1}[ -]?\\d{1}[A-Z]{1}\\d{1}\z/
validates :postal_code, format: { with: canadian_postal_code }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download