Ruby on Rails Password Validation

前端 未结 4 753
鱼传尺愫
鱼传尺愫 2020-12-29 08:16

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..4

相关标签:
4条回答
  • 2020-12-29 08:42

    this works for blank password on update action:

    validates :password, :presence => true, :on => :update,
     :if => lambda{ !password.nil? }
    
    validates :password,
      :confirmation => true,
      :length => { :minimum => 6},
      :if => lambda{ new_record? || !password.nil? }
    
    0 讨论(0)
  • 2020-12-29 08:52

    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
    
    0 讨论(0)
  • 2020-12-29 08:54

    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
    
    0 讨论(0)
  • 2020-12-29 08:54

    yet another variant

    validates_presence_of :password_digest
    
    validates_length_of :password, minimum: 6, if: Proc.new { |user| user.password.present? }
    
    0 讨论(0)
提交回复
热议问题