我的电话号码字段包含下拉列表中的国家/地区代码,现在我想根据下拉列表中国家/地区代码的选择验证最大长度验证。
profile.rb
validates_length_of :phone, :minimum => 10, :maximum => 10 if country_code = 91
答案 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
(免责声明:未经测试的代码)