根据国家/地区代码的选择验证电话号码的最小和最大长度

时间:2015-07-21 05:16:55

标签: ruby-on-rails ruby validation ruby-on-rails-4 model

我的电话号码字段包含下拉列表中的国家/地区代码,现在我想根据下拉列表中国家/地区代码的选择验证最大长度验证。

profile.rb

validates_length_of :phone, :minimum => 10, :maximum => 10 if country_code = 91

1 个答案:

答案 0 :(得分:2)

你做不到; if将在类定义时进行评估,而不是在验证时进行评估。您需要使用:if选项:

validates_length_of :phone, :minimum => 10, :maximum => 10,
    :if => Proc.new { |x| x.country_code == 91 }

或者你需要使用自定义验证器,例如:

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 be between #{min} and #{max} characters")
  end
end
validate :phone_number_is_correct_according_to_country_code

(免责声明:未经测试的代码)