带设备的自定义电子邮件验证器

bal*_*lki 2 validation ruby-on-rails email-validation devise ruby-on-rails-3

我按照wiki添加了一个带有设计的自定义电子邮件验证器。它有效,但每次验证都会打印两次错误,如下所示。如何解决这个问题? 错误信息!

更新:评论中链接的答案不起作用。仅当所有验证都在一次验证调用中完成时,它可能才有效。就我而言,一项验证是通过设计完成的,其他验证是由我添加的。需要明确的是,该模型如下所示:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me
  attr_accessible :email, :name

  before_save do |user|
    user.email = email.downcase
  end

  validates :name, presence: true, length: { maximum: 50 }
  validates :email, email: true, presence: true, reduce: true # This causes 'Email is Invalid' to be printed twice
end
Run Code Online (Sandbox Code Playgroud)

Yur*_*dev 5

如果您只需要更改设计用于电子邮件验证的正则表达式,您可以在以下位置执行此操作config/initializers/devise.rb

config.email_regexp = /\A[^@]+@[^@]+\z/
Run Code Online (Sandbox Code Playgroud)

然后您就不需要向电子邮件字段添加额外的验证。

  • 答案是过时的使用 1. ```Devise.email_regexp``` 或 2. https://github.com/plataformatec/devise/wiki/How-to:-Use-a-custom-email-validator-with-Devise (4认同)