ruby on rails - Validating min and max length of a phone number according to select of country code -
i have phone number field country code in drop-down, want validate max length validation according selection of country code in drop-down.
profile.rb
validates_length_of :phone, :minimum => 10, :maximum => 10 if country_code = 91
you can't that; if evaluate @ class definition, not @ validation time. either need use :if option:
validates_length_of :phone, :minimum => 10, :maximum => 10, :if => proc.new { |x| x.country_code == 91 } or need use custom validator, like:
phone_length_limits_by_country_code = { 91 => [10, 10] } def phone_number_is_correct_according_to_country_code min, max = *phone_length_limits_by_country_code[country_code] if phone.length < min || phone.length > max errors.add(:phone, "must between #{min} , #{max} characters") end end validate :phone_number_is_correct_according_to_country_code (disclaimer: untested code)
Comments
Post a Comment