Active Model驗證器
可與 ActiveModel::Validations::ClassMethods.validates_with
一同使用的簡單基本類別
class Person
include ActiveModel::Validations
validates_with MyValidator
end
class MyValidator < ActiveModel::Validator
def validate(record)
if some_complex_logic
record.errors.add(:base, "This record is invalid")
end
end
private
def some_complex_logic
# ...
end
end
繼承自 ActiveModel::Validator 的任何類別都必須實作一個稱為 validate
的方法,該方法接受一個 record
。
class Person
include ActiveModel::Validations
validates_with MyValidator
end
class MyValidator < ActiveModel::Validator
def validate(record)
record # => The person instance being validated
options # => Any non-standard options passed to validates_with
end
end
若要造成驗證錯誤,您必須直接從驗證器訊息新增至 record
的錯誤。
class MyValidator < ActiveModel::Validator
def validate(record)
record.errors.add :base, "This is some custom error message"
record.errors.add :first_name, "This is some complex validation"
# etc...
end
end
若要為 initialize 方法新增行為,請使用下列簽章
class MyValidator < ActiveModel::Validator
def initialize(options)
super
@my_custom_field = options[:field_name] || :first_name
end
end
請注意,驗證器僅在整個應用程式生命週期中初始化一次,而不在每次驗證執行時初始化。
最簡單的驗證個別屬性自訂驗證器的做法,是使用方便的 ActiveModel::EachValidator
類別。
class TitleValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add attribute, 'must be Mr., Mrs., or Dr.' unless %w(Mr. Mrs. Dr.).include?(value)
end
end
這個方法現在可與 validates
方法合併使用。詳情請參閱 ActiveModel::Validations::ClassMethods#validates
。
class Person
include ActiveModel::Validations
attr_accessor :title
validates :title, presence: true, title: true
end
當存在前提條件(例如 attr_accessor
出現)時,能夠存取使用該驗證器的類別會很有用。可透過建構函數中的 options[:class]
存取此類別。若要設定您的驗證器,請覆寫建構函數。
class MyValidator < ActiveModel::Validator
def initialize(options={})
super
options[:class].attr_accessor :custom_attribute
end
end
方法
屬性
[R] | 選項 |
公用類別方法
性質() 連結
傳回驗證器的種類。
PresenceValidator.kind # => :presence
AcceptanceValidator.kind # => :acceptance
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 103 def self.kind @kind ||= name.split("::").last.underscore.chomp("_validator").to_sym unless anonymous? end
新增(選項 = {}) 連結
接受可透過 options
讀取器取得的選項。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 108 def initialize(options = {}) @options = options.except(:class).freeze end
執行個體公用方法
性質() 連結
傳回此驗證器的種類。
PresenceValidator.new(attributes: [:username]).kind # => :presence
AcceptanceValidator.new(attributes: [:terms]).kind # => :acceptance
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 116 def kind self.class.kind end
驗證(記錄) 連結
在有驗證邏輯的子類別中覆寫此方法,必要時將錯誤新增至記錄的 errors
陣列。
來源:顯示 | 在 GitHub 上
# File activemodel/lib/active_model/validator.rb, line 122 def validate(record) raise NotImplementedError, "Subclasses must implement a validate(record) method." end