The new password and confirmation password must not be the same as the current password. how to limit it to a ruby on the rails?
I want to check current password, new password and confirm password in ruby on rails. When I click the Change Password button, it will ask me to enter my current, new and confirm password. but when I accidentally enter the same password in the "current password" and "new password" field, it shouldn't allow it. it should give an error message such as "current password and new password cannot be the same". but actually i dont know how to do it in ruby on rails. please help me if you know the answer. thank you in advance
source to share
I would add a custom line to my update method in the users_controller.rb file. I'm guessing it currently looks something like this?
def update
@user = User.find(params[:id])
if @user.update(usere_params)
redirect_to @user
else
render 'edit'
end
end
I would add a couple of lines to this file and make sure the new and current password do not match, and if so, return a validation error.
def update
@user = User.find(params[:id])
if params[:user][:new_password] == prams[:user][:current_password]
@user.errors.add(:new_password, 'Can not use current password')
end
if !@user.errors.any? and @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
This will cause it to if !@user.errors.any? and @user.update(user_params)
be false (because there is already an error) and just run the line render 'edit'
(which usually displays your validation errors if you've configured it that way).
source to share