Nappstir
Nappstir

Reputation: 995

Adding extra validations for Devise validatable

So currently validatable validates the presence of email and password. It can also validate an emails format. However, my user model requires more than just an email and password. I am also requiring a first, last and user name. So in order for me to validate the presence of these attributes I have to use rails validates as shown:

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

  validates :first_name, presence: true
  validates :last_name, presence: true
  validates :user_name, presence: true

end

I was wondering if there was a way to add first, last and user name to the validatable action. I have checked the devise.rb file and found the validatable config for a password_length and email_regexp but don't quite know how I can add additional attributes to the validatable function. Obviously this isn't a huge deal, but would be nice for cleaning up code in my User's model. Thank you for any responses to my questions.

Upvotes: 2

Views: 2428

Answers (1)

max
max

Reputation: 101976

While you could potentially monkeypatch Devise::Models::Validatable at runtime it would be rather foolish. Its going to take 5 times more code and potentially break upgrades.

The whole point of the module is to provide models with the basic validations needed for Devise to work out of the box.

What you are adding are validations which are specific to your application. As such it belongs in your application - don't try to stuff it back into the library.

Instead can clean up your model by:

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

  validates_presence_of :first_name, :last_name, :user_name
end

Upvotes: 5

Related Questions