egyamado egyamado - 11 months ago 86
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?


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 }