R – Combining validation errors in Rails

rubyruby-on-railsvalidation

For example, if I have a user with an email address that needs validating on presense and format:

validates_presence_of   :email_address, :message => "can't be blank"
validates_format_of     :email_address, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

If nothing is entered, how can I prevent both error messages appearing? I know for this scenario I wouldn't need the validates_presence_of, this is just an example. Thanks

Best Solution

In this example, you can add :allow_blank => true to the validates_format_of.

In general, I think it depends on the situation, most often it can be solved with clever usage of ActiveRecord validation options.