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] | options |
类公共方法
kind() 链接
返回验证器的类型。
PresenceValidator.kind # => :presence
AcceptanceValidator.kind # => :acceptance
new(options = {}) 链接
接受可通过 options
读取器获得的选项。
实例公共方法
kind() 链接
返回此验证器的类型。
PresenceValidator.new(attributes: [:username]).kind # => :presence
AcceptanceValidator.new(attributes: [:terms]).kind # => :acceptance