9

我正在尝试通过修改来自定义我的错误消息en.yml

en:
  errors:
    messages:
      blank: "This is a required field."

现在,每个具有validates presence: true验证器的空字段都会显示这条新消息。

我想找到要修改的消息类型列表。例如,如何自定义numericality验证器消息?还是greater_than验证者?

有什么建议在哪里可以找到这个?

4

4 回答 4

15

以下是您可以在en.yml文件中自定义的消息列表:

validates_acceptance_of
`:accepted` (“must be accepted”)
validates_associated
`:invalid` (“is invalid”)
validates_confirmation_of
`:confirmation` (“doesn’t match confirmation”)
validates_exclusion_of
`:exclusion` (“is reserved”)
validates_format_of
`:invalid` (“is invalid”)
validates_inclusion_of
`:inclusion`(“is not included in the list”)
validates_length_of
`:too_short` (“is too short (minimum is {{count}} characters)”)
`:too_long` (“is too long (maximum is {{count}} characters)”)
validates_length_of (with :is option)
`:wrong_length` (“is the wrong length (should be {{count}} characters)”)
validates_numericality_of
`:not_a_number` (“is not a number”)
validates_numericality_of (with :odd option)
`:odd` (“must be odd”)
validates_numericality_of (with :even option)
`:even` (“must be even”)
validates_numericality_of (with :greater_than option)
`:greater_than` (“must be greater than {{count}}”)
validates_numericality_of (with :greater_than_or_equal_to option)
`:greater_than_or_equal_to` (“must be greater than or equal to {{count}}”)
validates_numericality_of (with :equal_to option)
`:equal_to` (“must be equal to {{count}}”)
validates_numericality_of (with :less_than option)
`:less_than` (“must be less than {{count}}”)
validates_numericality_of (with :less_than_or_equal_to option)
`:less_than_or_equal_to` (“must be less than or equal to {{count}}”)
validates_presence_of
`:blank` (“can’t be blank”)
validates_uniqueness_of
`:taken` (“has already been taken”)
于 2013-07-28T03:22:17.550 回答
7

除了 Serg 的回答,您可以在此处找到内置验证器的密钥列表:

http://guides.rubyonrails.org/i18n.html#error-message-interpolation

于 2013-11-23T03:34:30.607 回答
0

它在命名空间链中找到错误消息。考虑一个对 name 属性进行验证的 User 模型,如下所示:

class User < ActiveRecord::Base
  validates :name, presence: true
end

在这种情况下,错误消息的键是 :blank。Active Record 会在命名空间中查找这个键:

activerecord.errors.models.[model_name].attributes.[attribute_name]
activerecord.errors.models.[model_name]
activerecord.errors.messages
errors.attributes.[attribute_name]
errors.messages

因此,在我们的示例中,它将按此顺序尝试以下键并返回第一个结果:

activerecord.errors.models.user.attributes.name.blank
activerecord.errors.models.user.blank
activerecord.errors.messages.blank
errors.attributes.name.blank
errors.messages.blank

希望它会有所帮助。谢谢

于 2013-07-28T04:26:31.943 回答
0

要添加到仅显示密钥的@MikeL 答案,可以在 rails very own github repository找到包含密钥和插值消息的完整列表。

于 2019-11-09T02:15:49.040 回答