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


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
  updated_at: 2007-07-16 21:54:27
  id: "2"
  firstname: Leon
  lastname: Bogaert
  password: ""
  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:


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:


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

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

  validates_confirmation_of :password,
                                :if => { |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?

hope this helps.

Or just use:

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


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

Thanks for the help!
I found a topic on that handles this same problem: