自定义电子邮件验证器与设计

时间:2015-10-30 13:14:05

标签: ruby-on-rails ruby-on-rails-3 validation devise email-validation

我按照wiki添加了设计的自定义电子邮件验证程序。它可以正常工作,但每次验证都会打印两次错误,如下所示。如何解决这个问题? Error message!

更新: 评论中的答案linked不起作用。它可能仅在所有验证都在一个验证调用中完成时才有效。在我的情况下,一个验证由设计完成,其他由我添加。需要说明的是,该模型如下所示:

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

2 个答案:

答案 0 :(得分:3)

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

config.email_regexp = /\A[^@]+@[^@]+\z/

然后您不需要在电子邮件字段中添加其他验证。

答案 1 :(得分:1)

您可以将电子邮件验证与Devise email_regexp一起使用,只需在config/initializers/devise.rb中进行更改

FROM(因为它可以验证某些不正确的电子邮件是否有效,例如emn178@gmail..com):

 config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

收件人:

 config.email_regexp = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i

我找到了此解决方案here