Rails自定义验证错误消息无效

时间:2015-06-28 20:53:57

标签: ruby-on-rails

我的理解是我可以自定义本地化文件中的错误消息。我目前正在尝试为我的用户模型上的无效用户名字段自定义错误消息:

User.rb

class User < ActiveRecord::Base
    validates :username,    length: { within: 3..25 },
                            format: /\A(?=.*[a-z])[a-z\d]+\Z/i,
                            uniqueness: true

en.yml(本地化文件)

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            username:
              format: "CUSTOM MESSAGE!"

但是,我收到的错误消息是默认的&#34;无效&#34;消息(或&#34;用户名无效&#34;如果我获得full_messages版本)。

1 个答案:

答案 0 :(得分:1)

看看hereformat中没有errors/messages个密钥。您需要覆盖invalid密钥。

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            username:
              invalid: "CUSTOM MESSAGE!"
相关问题