Reputation: 383
I have an Address
model and I need to validate the :zipcode
length depending on the :country
.
For example:
:country == 'us'
, maximum :zipcode
length should be 5
.:country == 'br'
, maximum :zipcode
length should be 8
.And so on...
I'm running Ruby on Rails 4.2.7.
Upvotes: 1
Views: 546
Reputation: 111
class Address < ActiveRecord::Base
ZIP_CODE_VALIDATION = { 'us' => 5, 'br' => 8 }.freeze
validate :zip_code_by_country
def max_length
ZIP_CODE_VALIDATION[country]
end
def zip_code_by_country
return unless zipcode.length > max_length
errors.add(:zipcode, "can't be greater than #{max_length}")
end
end
Upvotes: 2