Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip validation for some members in Devise model during password reset

My User (Devise) model also has name, city, nation, phone members.

In the create registration page - I validates_presence_of city, nation, phone, name, email, :on => :create

In the edit registration page - I validates_presence_of city, nation, phone, name, :on => :update

Now when I set a new password on forgot_password_page, it asks for the presence of city, nation, phone, name inside Devise::PasswordsController#update

How can I handle selective validations?

I am guessing it should be something like,

validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password

def not_recovering_password
  # what goes here
end
like image 507
Rahul Avatar asked Feb 05 '12 21:02

Rahul


2 Answers

I had a similar problem because when my User is created not all its fields are required. The other fields' presence is checked on: :update using a validation.

So this is how I solved:

validates :birthdate, presence: true, on: :update, unless: Proc.new{|u| u.encrypted_password_changed? }

The method encrypted_password_changed? is the one used in the Devise Recoverable.

like image 158
Pietro Avatar answered Oct 16 '22 21:10

Pietro


I came across this question looking for an answer to a similar question, so hopefully someone else finds this useful. In my case, I was dealing with legacy data that had missing information for fields that were previously not required but were later made required. Here's what I did, essentially, to finish the above code:


validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password

def not_recovering_password
  password_confirmation.nil?
end

Basically, it uses the absence/presence of the password_confirmation field to know if a user is trying to change/reset their password. If it's not filled, they are not changing it (and, thus, run your validations). If it is filled, then they are changing/resetting, and, thus, you want to skip your validations.

like image 24
GoGoCarl Avatar answered Oct 16 '22 22:10

GoGoCarl