跳至內容 跳至搜尋

Active Model EachValidator

EachValidator 是一個驗證器,它會遍歷選項雜湊中提供的屬性,並呼叫 `validate_each` 方法,傳入記錄、屬性和值。

所有 Active Model 驗證都是建立在此驗證器之上。

方法
C
N
V

屬性

[R] attributes

類別公開方法

new(options)

傳回新的驗證器實例。所有選項都可以透過 `options` 讀取器取得,不過 `:attributes` 選項會被移除,並透過 `attributes` 讀取器提供。

# File activemodel/lib/active_model/validator.rb, line 140
def initialize(options)
  @attributes = Array(options.delete(:attributes))
  raise ArgumentError, ":attributes cannot be blank" if @attributes.empty?
  super
  check_validity!
end

實例公開方法

check_validity!()

由初始化程式呼叫的掛勾方法,允許驗證所提供的引數是否有效。例如,當提供無效選項時,您可以引發 `ArgumentError`。

# File activemodel/lib/active_model/validator.rb, line 168
def check_validity!
end

validate(record)

對提供的記錄執行驗證。預設會呼叫 `validate_each` 來判斷是否有效,因此子類別應該覆寫 `validate_each` 並提供驗證邏輯。

# File activemodel/lib/active_model/validator.rb, line 150
def validate(record)
  attributes.each do |attribute|
    value = record.read_attribute_for_validation(attribute)
    next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
    value = prepare_value_for_validation(value, record, attribute)
    validate_each(record, attribute, value)
  end
end

validate_each(record, attribute, value)

在子類別中覆寫此方法,並提供驗證邏輯,必要時將錯誤新增到記錄的 `errors` 陣列中。

# File activemodel/lib/active_model/validator.rb, line 161
def validate_each(record, attribute, value)
  raise NotImplementedError, "Subclasses must implement a validate_each(record, attribute, value) method"
end