所有可能的模型验证错误

时间:2011-06-03 09:46:19

标签: ruby-on-rails ruby validation forms

我有一个包含大量字段和模型验证的表单。

如何返回可能引发的所有可能的验证错误?

我需要它为所有人编写区域设置。

我想得到一个这样的列表:

password blank
password too_short
password confirmation
login blank
login invalid
email blank
email too_short
email invalid

2 个答案:

答案 0 :(得分:12)

基本上是Pablo所说的,除了rails docs上的页面没有显示如何覆盖特定模型和字段的消息。这是我的一个应用程序的示例:

activerecord:
  errors:
    full_messages:
      format: "{{message}}"    
    #define standard error messages, which we can overide on per model/per attribute basis further down
    messages:
      inclusion: "{{attribute}} is not included in the list"
      exclusion: "{{attribute}} is reserved"
      invalid: "{{attribute}} is invalid"
      confirmation: "{{attribute}} doesn't match confirmation"
      accepted: "{{attribute}} must be accepted"
      empty: "{{attribute}} can't be empty"
      blank: "{{attribute}} can't be blank"
      too_long: "{{attribute}} is too long (maximum is {{count}} characters)"
      too_short: "{{attribute}} is too short (minimum is {{count}} characters)"
      wrong_length: "{{attribute}} is the wrong length (should be {{count}} characters)"
      taken: "{{attribute}} has already been taken"
      not_a_number: "{{attribute}} is not a number"
      greater_than: "{{attribute}} must be greater than {{count}}"
      greater_than_or_equal_to: "{{attribute}} must be greater than or equal to {{count}}"
      equal_to: "{{attribute}} must be equal to {{count}}"
      less_than: "{{attribute}} must be less than {{count}}"
      less_than_or_equal_to: "{{attribute}} must be less than or equal to {{count}}"
      odd: "{{attribute}} must be odd"
      even: "{{attribute}} must be even"
      record_invalid: "Validation failed: {{errors}}"    
    models:
      quiz:
        blank: "{{attribute}} can not be blank"
      user_session:
        blank: "{{attribute}} can not be blank"
        attributes:
          login:
            invalid: "Please enter your user name"   
          password:
            invalid: "Please note that passwords are case sensitive"  

我还更改了错误消息的基本格式,因为有时我不希望在消息的开头推送字段名称。所以,我改变了

errors:
  format: "{{attribute}} {{message}}"

errors:
  format: "{{message}}"    

这就是为什么我在随后的错误中指定{{attribute}},将其重新放入大多数但不是所有情况。

另请注意,我使用的是{{var}}而不是%{var}的旧语法。同样的原则也适用。

答案 1 :(得分:3)

最新的铁路翻译位于:rails-i18n

ActiveRecord错误位于 lang :错误和 lang :每个.yaml中的active_record。

在config / locales / en.yml下的应用程序中也是默认值。