【问题标题】:Custom validation error message based on regex基于正则表达式的自定义验证错误消息
【发布时间】: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


    【解决方案1】:

    您需要将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
    

    【讨论】:

      猜你喜欢
      • 2011-12-02
      • 2013-05-11
      • 2013-12-17
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多