ruby-on-rails - 基于正则表达式的自定义验证错误消息

标签 ruby-on-rails regex validation error-handling ruby-on-rails-5

我使用正则表达式和格式助手对应用程序中的密码字段进行了自定义验证。它工作正常。

我想为该验证添加自定义错误消息

我尝试添加消息验证器,并使用了相同的语言环境。但是他们似乎都没有帮助我。

原始验证:
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/

    相关文章:

    ruby-on-rails - Rails 渲染状态 : :not found missing template error

    ruby-on-rails - Rails 设计疑问 : Should/could I load the whole dictionary/table into memory?

    JavaScript - 正则表达式,是否有任何字符串的标记?

    java - 替换Java字符串中特定长度的子字符串

    Angular 7,验证 FormArray 内动态创建的一组复选框

    Android - Surface 无效

    java - 根据格式将字符串日期验证为有效日期的最佳方法是什么?

    ruby-on-rails - 格式化复数

    ruby - 正则表达式选择花括号之间的文本,Ruby

    ruby-on-rails - 使用 Devise 的 Rails 中的 session 变量是 'session' 还是 'user_session'?