I have a field string foo that must meet four conditions:
The first two are handled by :presence and :uniqueness validations. The latter two are easily handled by :format validations through regexes.
Is it possible to include multiple :format validation rules, with different :message values?
I'd like to avoid combining the two conditions into a single regex. In addition to the multiple messages, I think it's easier to read and write if they're distinct.
Ideally I'd like all of these to be wrapped up in a single validates call, but that's not strictly required.
According to the source code for the validates method, there's no way to do it; you get one :format key and one set of options as the hash value.
However, there's nothing stopping me from calling validates twice:
validates :foo,
:presence => true,
:uniqueness => true,
:format => {
:with => /^[\w\-]*$/,
:message => 'may only contain letters, digits, and hyphen'
}
validates :foo, :format => {
:with => /^(?!bar)/,
:message => 'may not start with "bar"'
}
This seems to work fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With