Sunday, February 3, 2008

Custom Rails Validations - Keeping it DRY

One of the validations that keeps coming up for us is zip/postal code. Sure you can use 'validates_format_of' with a regexp but it's nice to keep that regexp logic all in one place. We recently had to support Canadian Postal Codes so it was nice to update it just in one spot.

   def validates_as_zip_code(*attr_names)
configuration = {
:message => 'is an invalid zip code',
:with => /(^\d{5}$)|(^\d{5}-\d{4}$)|(^[ABCEGHJKLMNPRSTVXY]\d[A-Z] \d[A-Z]\d)/,
:allow_nil => false}
configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
validates_format_of attr_names, configuration
end

No comments: