[英]How to use ActiveModel::EachValidator in rails 5
How to validate specific attribute using ActiveModel::EachValidator
. 如何使用
ActiveModel::EachValidator
验证特定属性。 I have written the below snippet of code. 我已经编写了以下代码段。 This validation will not call on saving or validating object.
此验证不会调用保存或验证对象。
class EmailValidator < ActiveModel::EachValidator
def validate_each(record,attribute,value)
# Logic to check email is valid or not
end
end
This will work with rails 3. 这将适用于滑轨3。
A simple base class that can be used along with ActiveModel::Validations::ClassMethods#validates_with 可与ActiveModel :: Validations :: ClassMethods#validates_with一起使用的简单基类
class User
include ActiveModel::Validations
validates_with EmailValidator
end
class EmailValidator < ActiveModel::Validator
def validate(record)
# Logic to check email is valid or not
record.errors.add :email, "This is some complex validation"
end
end
Any class that inherits from ActiveModel::Validator must implement a method called validate which accepts a record. 从ActiveModel :: Validator继承的任何类都必须实现一个称为validate的方法,该方法接受一条记录。
To cause a validation error, you must add to the record's errors directly from within the validators message. 要导致验证错误,必须直接从验证者消息中添加到记录的错误中。
For more details you can check here . 欲了解更多详情,请点击这里 。
If you are looking for only email validation then you can try this. 如果您只寻找电子邮件验证,则可以尝试此操作。
class EmailValidator < ActiveModel::EachValidator
def validate_each(record, attr_name, value)
unless value =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
record.errors.add(attr_name, :email, options.merge(:value => value))
end
end
end
You can put your EmailValidator
class inside the models/concerns
directory. 您可以将您的
EmailValidator
类放在models/concerns
目录中。 Then inside your model you can validate the email attribute using the example below. 然后,在模型内部,您可以使用以下示例验证email属性。
class User < ApplicationRecord
validates :email, presence: true, email: true
end
Rails will look for the EmailValidator
class within the scope when it encounters email: true
then validate the attribute using the validate_each
method. 当Rails遇到
email: true
时,它将在范围内寻找EmailValidator
类email: true
然后使用validate_each
方法验证属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.