Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 validate presence of many columns with custom messages

Is there a way to specify many validations like this more concisely?

validates :col_a, :presence => {:message => 'col_a cannot be blank'}
validates :col_b, :presence => {:message => 'col_b cannot be blank'}
validates :col_c, :presence => {:message => 'col_c cannot be blank'}

I'd settle for a generic message if I had to.

like image 410
danh Avatar asked Feb 20 '13 21:02

danh


1 Answers

You can give multiple field names to a validator

validates :col_a, :col_b, :col_c, :presence => true

You can specify multiple validators in the same line.

validates :col_a, :col_b, :col_c, :presence => true, :numericality => true

The full error message will contain the field name. You don't need to add the field name prefix. If you want to use a custom message then:

validates :col_a, :col_b, :col_c, :presence => {:message => "empty value found"}
like image 80
Harish Shetty Avatar answered Oct 16 '22 04:10

Harish Shetty