fl00r fl00r - 1 year ago 83
Ruby Question

All possible model validation errors

I have got a form with a bunch of fields and model validations.

How can I return all possible validation errors that can be raised?

I need it to write locales for all of them.

I want to get a list like this:

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


Answer Source

Basically what Pablo says, except that the page on the rails docs doesn't show how to override the messages for a particular model and field. here's an example from one of my apps:

      format: "{{message}}"    
    #define standard error messages, which we can overide on per model/per attribute basis further down
      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}}"    
        blank: "{{attribute}} can not be blank"
        blank: "{{attribute}} can not be blank"
            invalid: "Please enter your user name"   
            invalid: "Please note that passwords are case sensitive"  

I've also changed the basic format for error messages, as sometimes i didn't want the field name shoved at the start of the message. So, i changed

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


  format: "{{message}}"    

Which is why i then specify {{attribute}} in my subsequent errors, to put it back in in most but not all cases.

Note also that i'm using the old syntax of {{var}} rather than %{var}. The same principles apply though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download