egyamado egyamado - 7 months ago 57
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 https://github.com/globaldev/going_postal but i think it's over kill just for validation.

Is there another way to write validation for Post Code?

Answer

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 }