我使用正则表达式和格式助手对应用程序中的密码字段进行了自定义验证。它工作正常。
我想为该验证添加自定义错误消息。
我尝试添加消息验证器,并使用了相同的语言环境。但是他们似乎都没有帮助我。
原始验证:has_secure_password
VALID_PASSWORD_REGEX = /\A(?=.*[a-z])(?=.*[A-Z])(?=.*[\W])(?=.*[\d])[\S]{8,15}\z/
validates :password, format: { with: VALID_PASSWORD_REGEX }, allow_nil: true
使用消息验证器时:has_secure_password
VALID_PASSWORD_REGEX = /\A(?=.*[a-z])(?=.*[A-Z])(?=.*[\W])(?=.*[\d])[\S]{8,15}\z/
validates :password, format: { with: VALID_PASSWORD_REGEX }, allow_nil: true,
message: ' should contain uppercase, lowercase, number and special character. Between 8 and 15 characters long'
显示的错误消息是:Unknown validator: 'MessageValidator'
当我写:message => "Error message"
而不是message: "Error message"
时出现了相同的错误
使用语言环境时写原始验证。
en.yml文件更改为:en:
activemodel:
attributes:
employee:
password: "Password"
errors:
models:
employee:
attributes:
password: "should contain at least one uppercase, lowercase, numeric and special character. Between 8 and 15 characters long"
该应用程序正常运行,没有任何错误消息。但是,当输入无效密码时,显示的错误消息是
PS:为了在 View (application.html.erb)中显示错误消息,我使用了:
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
最佳答案
您需要将message
键放在format
中,否则会认为您正在尝试应用MessageValidator
validates :password, format: {
with: VALID_PASSWORD_REGEX,
message: 'should contain uppercase, lowercase, number and special character. Between 8 and 15 characters long'
},
allow_nil: true
关于ruby-on-rails - 基于正则表达式的自定义验证错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48135280/