Skip validation for some members in Devise model during password reset

前端 未结 4 1149
Happy的楠姐
Happy的楠姐 2021-01-18 12:09

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,

相关标签:
4条回答
  • 2021-01-18 12:31

    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.

    0 讨论(0)
  • 2021-01-18 12:34

    Got an answer from José - https://github.com/plataformatec/devise/issues/1623

    0 讨论(0)
  • 2021-01-18 12:36

    In the Devise model you can override reset_password! and use your own validations. For example:

    def reset_password!(new_password, new_password_confirmation)
      self.password = new_password
      self.password_confirmation = new_password_confirmation
    
      validates_presence_of     :password
      validates_confirmation_of :password
      validates_length_of       :password, within: Devise.password_length, allow_blank: true
    
      if errors.empty?
        clear_reset_password_token
        after_password_reset
        save(validate: false)
      end
    end
    
    0 讨论(0)
  • 2021-01-18 12:45

    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.

    0 讨论(0)
提交回复
热议问题