Rails獨立運行所有驗證器,以便一次給出所有錯誤的數組。這是爲了避免所有常見的情況:
請輸入密碼。
pass
你輸入的密碼是無效的:它不含有一個數字。
1234
你輸入的密碼是無效的:它不包含一個字母。
a1234
你輸入的密碼是無效的:它不長至少六個字符。
ab1234
你輸入的密碼是無效的:你不能在一個序列中使用三個或多個連續字符。
piss off
你輸入的密碼是無效的:它不含有一個數字。
有兩件事你可以做,我知道。要麼包括您的自定義驗證器下的所有內容,在這種情況下,所有內容都在您的控制之下,或者使用:unless => Proc.new { |x| x.birthday.nil? }
修飾符來明確限制您的驗證器在其中斷的情況下運行。我肯定會建議第一種方法;第二是哈克。
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