【发布时间】:2018-06-16 13:05:36
【问题描述】:
我使用正则表达式和格式助手对我的应用程序中的密码字段进行了自定义验证。它工作正常。
我想为该验证添加一个自定义错误消息。
我尝试添加消息验证器并使用相同的语言环境。但他们似乎都没有帮助我。
原始验证:
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:为了在视图中显示错误消息(application.html.erb),我使用了:
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %>"><%= message %></div>
<% end %>
【问题讨论】:
标签: ruby-on-rails regex validation error-handling ruby-on-rails-5