Rails 独立运行所有验证器,以便一次为您提供所有错误的数组。这样做是为了避免太常见的情况:
请输入密码。
pass
您输入的密码无效:它不包含数字。
1234
您输入的密码无效:它不包含字母。
a1234
您输入的密码无效:密码长度至少为六个字符。
ab1234
您输入的密码无效:您不能在一个序列中使用三个或更多连续字符。
piss off
您输入的密码无效:它不包含数字。
据我所知,你可以做两件事。要么将所有内容包含在您的自定义验证器下,在这种情况下,一切都在您的控制之下,或者使用:unless => Proc.new { |x| x.birthday.nil? }
修饰符明确限制您的验证器在它会中断的情况下运行。我肯定会建议第一种方法;第二个是hacky。
def is_21_or_older
if birthday.blank?
errors.add(:birthday, "Must have birthday")
elsif birthday > 21.years.ago.to_date
errors.add(:birthday, "Must 21 Or Older")
end
end
也许更好的方法是保留存在验证器,当它看到另一个验证器的条件失败时退出您的自定义验证器。
def is_21_or_older
return true if birthday.blank? # let the other validator handle it
if birthday > 21.years.ago.to_date
errors.add(:birthday, "Must 21 Or Older")
end
end