views:

80

answers:

2

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

+3  A: 

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.

Ben
Thanks, that does the job fine. When I think of a situation where I'd want more than that I'll post it up.
sebastyuiop
+1  A: 

You can also introduce a conditional :if, such as:

validates_format_of :email_address, :with => EMAIL_REGEXP, :if => :email_address?

The email_address? method should return true only if that field has a non-blank value. That can be very handy for situations like this.

tadman
Yeh this would be more relavent if the conditional could use another validates_foo... validates_format_of :email_address, :with => EMAIL_REGEXP, :if => {validates_whatever_of :email_address}I know that won't work, but that explains my initial question a bit more clearly.
sebastyuiop
I think it'd be a lot better if validations could be chained, like you say, but there's no support for that yet. They all run, all the time, and each has a chance to introduce an error message.
tadman