Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add password validation while updating password

I have following validation for a user in rails project

validates :password,   presence: true, format: { with: /^[a-zA-Z0-9]+$/, multiline: true }, on: :create

How can I validate the password in devise_token_auth password update

like image 665
CR7 Avatar asked Jun 08 '26 09:06

CR7


1 Answers

There you go:

validates :password,   presence: true, format: { with: /^[a-zA-Z0-9]+$/, multiline: true }, if: :password_validation

def password_validation
  new_record? || password_digest_changed?
end

This will trigger the validation on password in two cases:

  1. When it's a new record.
  2. When the password change is attempted.

Assuming you are using has_secure_password, it gives password and password_confirmation as attributes, and password_digest as the field. Rails exposes _changed? method to check if the given attribute has changed (is dirty) (and not persisted yet).

u = User.last
u.email = '[email protected]'
u.email_changed? #=> true
u.save #=> true
u.email_changed? #=> false
like image 76
kiddorails Avatar answered Jun 11 '26 02:06

kiddorails



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!