Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

has_secure_password: how to require minimum length

How do I require that a password has a minimum length when using has_secure_password in Rails 3.1? I tried to do:

class User < ActiveRecord::Base
    ... 
    validates :password, presence: { on: create }, length { minimum: 8 }
    ...
end

but then the validation fails with password "too short" on update when password is not provided in form params. For other attributes length is only validated if the value for the field is provided. Is this a bug in the has_secure_password implementation or am I doing something wrong?

like image 579
Peder Avatar asked Oct 11 '22 16:10

Peder


1 Answers

You should do something like:

validates :password, presence: { on: create }, length { minimum: 8 }, :if => :password_changed?
like image 92
apneadiving Avatar answered Oct 14 '22 02:10

apneadiving