quy*_*tdc 2 ruby-on-rails devise
我正在尝试在我使用设计进行用户管理的项目中添加自定义密码验证。我成功创建用户,或者手动更改用户密码。但是,如果我退出控制台并再次打开它,我的有效用户(最后一步)将变得无效。
我正在使用 devise 4.6.2 和rails 5.2.0
这是我的用户模型
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
Run Code Online (Sandbox Code Playgroud)
当我在控制台中尝试时
u = User.new(email: 'test@test.com', password: 'Abc123!', password_confirmation: 'Abc123!')
u.valid? # TRUE
u.save
Run Code Online (Sandbox Code Playgroud)
然后
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
Run Code Online (Sandbox Code Playgroud)
我做错了什么吗?
小智 7
User.last 没有密码。这就是引发错误的原因。
非常相似的问题: https://github.com/plataformatec/devise/wiki/How-To :-Set-up-simple-password-complexity-requirements
Anw,您可以在 config devise.rb 上设置密码长度。
config.password_length = 7..128
Run Code Online (Sandbox Code Playgroud)
如果你想在 devise.rb 上设置密码格式,请尝试这个 gem https://github.com/phatorx/devise_security_extension