Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom email validator with devise

I followed the wiki to add a custom email validator with devise. It works but the errors are printed twice once for each validation like below. How to fix this? Error message!

Update: The answer linked in the comment does not work. It probably works only if all validations are done in one validates call. In my case one validation is done by devise and other is added by me. To be clear, the model looks like below:

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
like image 480
balki Avatar asked Jul 27 '26 18:07

balki


2 Answers

If you just need to change the regular expression that devise is using for email validation, you can do it in config/initializers/devise.rb:

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

Then you won't need to add additional validation to the email field.

like image 167
Yury Lebedev Avatar answered Jul 29 '26 10:07

Yury Lebedev


You can use email validation with Devise email_regexp, just change in config/initializers/devise.rb

FROM (because it validates some incorrect emails as valid, like [email protected]):

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

TO:

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

I found this solution here.

like image 31
Polina Avatar answered Jul 29 '26 11:07

Polina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!