Meydjer Luzzoli
Meydjer Luzzoli

Reputation: 383

ActiveRecord multiple custom length validation

I have an Address model and I need to validate the :zipcode length depending on the :country.

For example:

And so on...

I'm running Ruby on Rails 4.2.7.

Upvotes: 1

Views: 546

Answers (1)

Fercell
Fercell

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

Related Questions