【问题标题】:Custom email validator with devise带有设计的自定义电子邮件验证器
【发布时间】:2015-10-30 13:14:04
【问题描述】:

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

更新: 评论中的答案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

【问题讨论】:

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


【解决方案1】:

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

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

那么您将不需要向电子邮件字段添加额外的验证。

【讨论】:

【解决方案2】:

您可以通过 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 2021-05-26
    • 1970-01-01
    • 2019-12-25
    • 2019-05-28
    • 2014-04-07
    • 1970-01-01
    相关资源
    最近更新 更多