validating password: when empty, don't save it!

Hi,

Users can edit their own passwords in my app. But when they leave both password-fields (_confirmation) empty, they get "" as their password. Is their a way to get around this problem? This is my userobject when I try to save it:

--- !ruby/object:User attributes:   updated_at: 2007-07-16 21:54:27   id: "2"   firstname: Leon   lastname: Bogaert   password: ""   account_number: 53.76.68.829   email: leon@tim-online.nl   created_at: 2007-03-29 00:24:21 password_confirmation: ""

Thanks in advance!

Add this in your User model:

  validates_presence_of :password   validates_presence_of :password_confirmation   validates_confirmation_of :password

p.s. I would use the restful_authentication or act_as_authenticated plugins for logins :slight_smile:

PatRoy,

Thanks for your quick reply. I don't use a standard plugin for educational purposes.

When an user does not fill in his or her password it shouldn't give an error. The system should just not update the password. This is (a part of) my usermodel:

  MINIMUM_PASSPHRASE_LENGTH = 8   MAXIMUM_PASSPHRASE_LENGTH = 64

  validates_presence_of :password,                                 :on => :create,                 :message => "^Geen wachtwoord ingevuld"

  validates_length_of :password,                                 :in => MINIMUM_PASSPHRASE_LENGTH..MAXIMUM_PASSPHRASE_LENGTH,                                 :if => Proc.new { |u| ! u.password.blank? },                 :too_long => "Het wachtwoord mag maximaal %d tekens lang zijn",                 :too_short => "^Het wachtwoord moet minimaal %d tekens lang zijn"

  validates_confirmation_of :password,                                 :if => Proc.new { |u| ! u.password.blank? },                 :message => "^De wachtwoorden komen niet overeen"

when you save your object ...

Thanks PayRoy!

But I would rather not do that in my controller. It's kind of business logic. So it would be more suitable to place it in my model.

Thanks Patroy! But I would like to implement the code in my model. It's kind of business logic so I would like to implement it in the proper place.

Hi I just stumbled on to this

heres my solution:

  validates_presence_of :password, :password_confirmation,                         :on => :update,                         :if => :req_password?

def req_password?   !password.blank? end

hope this helps.

Or just use:

validates_confirmation_of :password,   :message => "must match confirm password",   :if => Proc.new { |u| !u.password.blank? }

Wim

Meng wrote:

Thanks Meng and Wim! But if the password is empty it will be saved to the database (empty). I think I'll use the empty? function to set the password to the old value.

Thanks for the help! I found a topic on tweakers.net that handles this same problem: http://gathering.tweakers.net/forum/list_messages/1035239/15