如何自定义错误消息以验证数字子选项?

时间:2012-06-12 12:14:52

标签: ruby-on-rails-3 validation activerecord

在验证ActiveRecord模型中字段的数字时,如何自定义子选项的错误消息?

示例:

validates :month, :numericality => {
  :greater_than_or_equal_to => 1,
  :less_than_or_equal_to    => 12
}

在这种情况下,如果'month'属性超过12,我想提供自定义错误消息,而不是默认的“必须小于或等于12”。怎么做到这一点?

2 个答案:

答案 0 :(得分:8)

如果您不想使用自定义验证程序,则可以使用en.yml文件。假设“post”是您的模型名称,它提供了特定于年龄的消息,特定于帖子的消息和通用(所有模型)消息的示例。

en:
  activerecord:
    errors:
      models:
        post:
          attributes:
            age:
              less_than_or_equal_to: "Age-specific error" # Applies only to post.age
          less_than_or_equal_to: "Post-specific error" # Applies to all other fields for a post
      messages:
        less_than_or_equal_to: "Generic error" # Applies to all other models

答案 1 :(得分:1)

如果要根据模型自定义错误消息,可以使用以下语法:

validates_numericality_of :month, 
    greater_than_or_equal_to: 1,
    less_than_or_equal_to: 12,
    message: "My custom error message"

您还可以使用此语法根据特定条件自定义错误消息:

validates_numericality_of :month, 
    greater_than_or_equal_to: 1,
    message: "Too small"

validates_numericality_of :month, 
    less_than_or_equal_to: 12,
    message: "Too big