自定义EmailValidator不起作用

晶须

我有一个基于ruby指南的自定义电子邮件验证器类:

class EmailValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
     record.errors[attribute] << (options[:message] || "is not an email")
    end
  end
end

此类位于app / validators / email_validator.rb中

模型:

class User < ActiveRecord::Base

    validates :name, :email, presence: true
validates :email, email: true

end

错误:

`rescue in block in validates': Unknown validator: 'EmailValidator' (ArgumentError)

运行测试(rspec)时出现此错误。

Paritosh piplewar

试试这个

def validate_each(record, attribute, value)
    begin
      r =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i
    rescue Exception => e
      r = false
    end
    record.errors[attribute] << (options[:message] || "is not an email") unless r
end

专业类型:

看起来您正在寻找电子邮件验证程序,为什么不使用此验证程序

require 'mail'
class EmailValidator < ActiveModel::EachValidator
  def validate_each(record,attribute,value)
    begin
      m = Mail::Address.new(value)
      # We must check that value contains a domain and that value is an email address
      r = m.domain && m.address == value
      t = m.__send__(:tree)
      # We need to dig into treetop
      # A valid domain must have dot_atom_text elements size > 1
      # [email protected] is excluded
      # treetop must respond to domain
      # We exclude valid email values like <[email protected]>
      # Hence we use m.__send__(tree).domain
      r &&= (t.domain.dot_atom_text.elements.size > 1)
    rescue Exception => e   
      r = false
    end
    record.errors[attribute] << (options[:message] || "is invalid") unless r
  end
end

一定要在之前加载此类,我想您知道要这样做(因为许多其他答案已经很好地描述了它)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章