Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip email validation in Devise

In Devise Validatable module contains validates_uniqueness_of :email, :allow_blank => true, :if => :email_changed? How to disable this validator?

like image 768
maxs Avatar asked Feb 09 '12 12:02

maxs


2 Answers

Per Devise's own documentation on the Validatable module...

Validatable creates all needed validations for a user email and password. It's optional, given you may want to create the validations by yourself. Automatically validate if the email is present, unique and its format is valid. Also tests presence of password, confirmation and length.

Bolding my emphasis.

You should disable the Validatable module and roll your own validations.

devise :database_authenticatable, :registerable, :rememberable,
       :trackable, :timeoutable, :confirmable, :recoverable, :lockable
       # :validatable <-- this one needs to go

Review the contents of lib/devise/models/validatable.rb and pull the relevant sections into your own User class. For the current 3.2.x version line, it should look something like this...

class User < ActiveRecord::Base

  # From Devise module Validatable
  validates_presence_of   :email, if: :email_required?
  validates_uniqueness_of :email, allow_blank: true, if: :email_changed?
  validates_format_of     :email, with: email_regexp, allow_blank: true, if: :email_changed?

  validates_presence_of     :password, if: :password_required?
  validates_confirmation_of :password, if: :password_required?
  validates_length_of       :password, within: password_length, allow_blank: true

  # [ ... ] The rest of your model stuff

  protected

  # From Devise module Validatable
  def password_required?
    !persisted? || !password.nil? || !password_confirmation.nil?
  end

  # From Devise module Validatable
  def email_required?
    true
  end

end

Then make whatever changes are necessary.

A real world scenario: I use the Paranoia gem on a number of projects, which won't work with this module. So I remove it and customize the email uniqueness check to read as...

validates_uniqueness_of :email, scope: :deleted_at
like image 120
Frank Koehl Avatar answered Nov 11 '22 02:11

Frank Koehl


Depending on your needs you may not need to completely tear out the Validatable module. If you just want to allow empty strings in the email column then you can override the email_required? method...

class User
...
def email_required?
  false
end
like image 4
abaldwin99 Avatar answered Nov 11 '22 01:11

abaldwin99