Reputation: 534
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
Upvotes: 0
Views: 570
Reputation: 211560
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.
Upvotes: 1
Reputation: 8348
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.
Upvotes: 3