2

I am trying to add custom password validation in a project which I use devise for user management. I am successful to create user, or manually change user password. However, if I exit my console and open it again, my valid user ( at last step ) becomes invalid.

I am using devise 4.6.2 and rails 5.2.0

Here is my user model

class User < ApplicationRecord


  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  validates :password, 
            format: { with: /\A(?=.*\d)(?=.*[A-Z])(?=.*\W)[^ ]{7,}\z/,
                      message: 'Password should have more than 7 characters including 1 uppercase letter, 1 number, 1 special character'
                    }

end

When I try in my console

u = User.new(email: 'test@test.com', password: 'Abc123!', password_confirmation: 'Abc123!')
u.valid? # TRUE
u.save

Then

u = User.last # return exact above user
u.valid? # FALSE
u.errors.full_messages # Password Password should have more than 7 characters including 1 uppercase letter, 1 number, 1 special character

Is there anything that I am doing wrong?

quyetdc
  • 1,485
  • 1
  • 14
  • 24

2 Answers2

7

There's no password for User.last. That reason why error's raised.

Very similar issue: https://github.com/plataformatec/devise/wiki/How-To:-Set-up-simple-password-complexity-requirements

Anw, u can set length of password on config devise.rb.

config.password_length = 7..128

Incase u want to set password format on devise.rb, try this gem https://github.com/phatworx/devise_security_extension

Duyet Nguyen
  • 543
  • 3
  • 11
3

Thanks, I come up with a solution using custom validator

class User < ApplicationRecord
  validate :password_regex

  private

  def password_regex
    return if password.blank? || password =~ /\A(?=.*\d)(?=.*[A-Z])(?=.*\W)[^ ]{7,}\z/

    errors.add :password, 'Password should have more than 7 characters including 1 uppercase letter, 1 number, 1 special character'
  end
end
quyetdc
  • 1,485
  • 1
  • 14
  • 24