我在User
型号代码中为我的用户密码添加了密码正则表达式,如下所示。
validates :password, presence: true, length: { minimum: 6 }
validate :password_complexity
has_secure_password
def password_complexity
if password.present? and not password.match(/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d). /)
errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"
end
end
当我尝试Password1
时,它不会接受它。任何想法,为什么这不会采取?
答案 0 :(得分:1)
我非常肯定,就性能和处理而言,即使可能,使用单个Regexp也可能效果不佳。
此外,使用String#match
比使用String#=~
要慢,因为返回值不同。
我会将需求分成数字或Regexp并保持简单,如下所示:
def password_complexity
return unless password.present?
unless password =~ /[a-z]/ && password =~ /[A-Z]/ && password =~ /[\d]/
errors.add :password, "must include at least one lowercase letter, one uppercase letter, and one digit"
end
end
阅读和维护起来有点简单。它还允许您稍后将错误消息分解为更具体的错误,可能是这样的:
def password_complexity
return unless password.present?
errors.add :password, "must include at least one lower case letter." unless password =~ /[a-z]/
errors.add :password, "must include at least one upper case letter." unless password =~ /[A-Z]/
errors.add :password, "must include at least one digit." unless password =~ /[\d]/
end
答案 1 :(得分:-1)