Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple format validations in Rails

I have a field string foo that must meet four conditions:

  • It must be non-blank
  • It must be unique for all records
  • It must only contain letters, digits, and hypens
  • It must not start with the string "bar"

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.

like image 266
Craig Walker Avatar asked Mar 27 '12 17:03

Craig Walker


1 Answers

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.

like image 149
Craig Walker Avatar answered Nov 06 '22 21:11

Craig Walker