我正在用Rails创建博客应用程序。
Ruby版本-> 2.5.1Rails版本-> 5.1.7
我有一个用于验证密码的用户模型,并且它的确认必须匹配。
validates :password, presence: true, length: {minimum: 6, maximum: 20}
validates :password, confirmation: {case_sensitive: true , message: "Passwords don't match"}
现在,当我使用不同的密码提交表单并得到确认时,在顶部显示的错误消息是:
2 errors found.
Password confirmation Passwords don't match
Password confirmation doesn't match Password
以及我的期望:
1 error found.
Passwords don't match
这是表单视图的代码,如果需要:
#The errors partial is just iterating over the user object errors and displaying them.
<%= render 'shared/errors', obj: @user %>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :password %>
</div>
<div class="col-sm-8">
<%= f.password_field :password, class: "form-control", placeholder: "Enter password" %>
</div>
</div>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :password_confirmation, 'Confirm Password' %>
</div>
<div class="col-sm-8">
<%= f.password_field :password_confirmation, class: "form-control", placeholder: "Enter password again" %>
</div>
</div>
更新的用户模型:
class User < ActiveRecord::Base
has_many :articles
validates :username, presence: true, uniqueness: {case_sensitive: false},
length: {minimum: 3, maximum: 25}
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 105 },
uniqueness: { case_sensitive: false },
format: { with: VALID_EMAIL_REGEX }
validates :password, presence: true, length: {minimum: 6, maximum: 20}
validate :password_check
before_save { self.email = email.downcase }
has_secure_password
private
def password_check
# Check for nils and blanks
errors.add(:base, "Passwords don't match") if password != password_confirmation
end
end
我认为activerecord的错误消息和您添加的自定义错误消息会同时打印。当您从验证中删除自定义错误消息时,我认为问题会解决。
如果要添加自定义错误消息,请如下更改default activerecord error message:
# config/locales/en.yml
en:
activerecord:
errors:
models:
user:
attributes:
password:
confirmation: "don't match"
UPDATE
如果以上方法不能解决问题,则可以编写自定义验证:
删除validates :password, confirmation: ..
validate :confirm_password
private
def confirm_password
return if password == password_confirmation
errors.add(:password, "don't match")
end
不需要配置选项,因为默认为sensitive_case: true
,如果导致出现双重错误消息,则为message
。
validates :password, confirmation: true
会给你
1 error found.
Password confirmation doesn't match Password
如果您确实需要该自定义消息,则应编写自己的validate方法并将错误添加到base
:
# validates :password, confirmation: {case_sensitive: true , message: "Passwords don't match"}
validate :password_check
private
def password_check
# Check for nils and blanks
errors.add(:base, "Passwords don't match") if password != password_confirmation
end