Rails validation error messages: Displaying only one per field

Posted by Sergio Oliveira Jr. on Stack Overflow See other posts from Stack Overflow or by Sergio Oliveira Jr.
Published on 2010-04-02T21:52:55Z Indexed on 2010/04/08 3:53 UTC
Read the original article Hit count: 477

Filed under:
|

Rails has an annoying "feature" which displays ALL validation error messages associated with a given field. So for example if I have 3 validates_XXXXX_of :email, and I leave the field blank I get 3 messages in the error list. This is non-sense. It is better to display one messages at a time. If I have 10 validation messages for a field does it mean I will get 10 validation error messages if I leave it blank?

Is there an easy way to correct this problem? It looks straightforward to have a condition like: If you found an error for :email, stop validating :email and skip to the other field.

Ex:

validates_presence_of :name
validates_presence_of :email
validates_presence_of :text

validates_length_of :name, :in => 6..30
validates_length_of :email, :in => 4..40
validates_length_of :text, :in => 4..200

validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+.)+[a-z]{2,})$/i

<%= error_messages_for :comment %> gives me:

7 errors prohibited this comment from being saved
There were problems with the following fields:

Name can't be blank
Name is too short (minimum is 6 characters)
Email can't be blank
Email is too short (minimum is 4 characters)
Email is invalid

Text can't be blank
Text is too short (minimum is 4 characters)

© Stack Overflow or respective owner

Related posts about rails

Related posts about validation