Cascading validation

Hi all,

I want to provide the most meaningful error message possible when a user enters the wrong data, so I have a series of validation rules like so:

validates_presence_of :name     validates_length_of :name,                         :in => 3..30     validates_format_of :name,                         :with => /^[a-z]/i,                         :message => 'begins with a non alphabetical character'     validates_format_of :name,                         :with => /^([a-z][a-z0-9_-]*)$/i,                         :message => 'contains non alphanumeric characters'     validates_uniqueness_of :name

Problem is when one is wrong I'd only like for the first error to be shown, not all of them. I can use an :if => condition type clause but I'm not sure how to do it without duplicating a lot, i.e. (pseudo code)

validates_presence_of :name     validates_length_of :name,                         :if => not name.nil?,                         :in => 3..30     validates_format_of :name,                         :with => /^[a-z]/i,                         :if => not name.nil? and name in 3..30,                         :message => 'begins with a non alphabetical character'

Any ideas?

I want to provide the most meaningful error message possible when a user enters the wrong data, so I have a series of validation rules like so:

[snip]

Problem is when one is wrong I'd only like for the first error to be shown, not all of them. I can use an :if => condition type clause but I'm not sure how to do it without duplicating a lot, i.e. (pseudo code)

Put the code you are duplicating into a private method and call it from your :if condition.

See the validations in the model from Rick Olson's Restful Authentication plugin for an example:

http://svn.techno-weenie.net/projects/plugins/restful_authentication/generators/authenticated/templates/model.rb

Regards, Andy Stewart