Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails Password Validation

So I have interesting password validation requirements:

  • When a user signs up, I want them to have to type in password and confirm and be between 6..40 (GOT THIS WORKING 100%)

  • When a user updates their profile, the same validation rules apply (GOT THIS WORKING 100%)

  • When an admin adds a user, they only have to enter the password once and it should be validated (NOT WORKIG)

  • When an admin edits a user and the password field is blank, it shouldn't update the password, if they type something, it should be validated. (PARTIAL WORKING)

    validates :password, :presence => true,
                       :confirmation => true,
                       :length => {:within => 6..40},
                       :unless => :force_submit
    

The only cases I can't cover are when an admin adds a user, it is not validated and when an admin edits a user (and types in a password) it is not validated.

the :force_submit is passed in from the admin form, so the password isn't validated. (So the case of an updating empty password works)

Any ideas/magic?

like image 833
Chris Muench Avatar asked Feb 25 '11 23:02

Chris Muench


2 Answers

Building slightly on the accepted answer, here's the code that I used in a Rails project at work. (Note: We're using devise to handle user authentication, and devise_invitable to create new users.)

PASSWORD_FORMAT = /\A
  (?=.{8,})          # Must contain 8 or more characters
  (?=.*\d)           # Must contain a digit
  (?=.*[a-z])        # Must contain a lower case character
  (?=.*[A-Z])        # Must contain an upper case character
  (?=.*[[:^alnum:]]) # Must contain a symbol
/x

validates :password, 
  presence: true, 
  length: { in: Devise.password_length }, 
  format: { with: PASSWORD_FORMAT }, 
  confirmation: true, 
  on: :create 

validates :password, 
  allow_nil: true, 
  length: { in: Devise.password_length }, 
  format: { with: PASSWORD_FORMAT }, 
  confirmation: true, 
  on: :update
like image 88
Tom Lord Avatar answered Sep 18 '22 19:09

Tom Lord


The below seem to meet my requirements...I am actually now requiring a confirmation for all users.. (It makes the view cleaner). But on an update I am allowing blanks.

  validates :password, :presence => true,
                       :confirmation => true,
                       :length => {:within => 6..40},
                       :on => :create
  validates :password, :confirmation => true,
                       :length => {:within => 6..40},
                       :allow_blank => true,
                       :on => :update
like image 23
Chris Muench Avatar answered Sep 17 '22 19:09

Chris Muench