Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Validation: Limit input to specific values

I'm looking for "the Rails Way" to write a validation that limits acceptable input values to a predetermined list.

In my case, I want to only accept the values "-5", "-2", "+2", "+5", and nil. However, I think this is best as a general question: how do you predefine a list of acceptable entry values in a Rails model?

Thanks!

like image 861
Andrew Avatar asked Jan 18 '11 23:01

Andrew


3 Answers

validates_inclusion_of should work. For example:

  validates_inclusion_of :attr, :in => [-5, -2, 2, 5], :allow_nil => true
like image 171
Costa Walcott Avatar answered Sep 21 '22 13:09

Costa Walcott


You want to use validates_inclusion_of with the :in and :allow_nil options.

validates_inclusion_of :field, :in => %w(-5 -2 2 5), :allow_nil => true

You'll probably also want to use in conjunction with validates_numericality_of

like image 23
Peter Brown Avatar answered Sep 24 '22 13:09

Peter Brown


Rails 3+

The modern way to do this is the following:

validates :field, inclusion: { in: [ -5, -2, 2, 5 ], allow_blank: true, message: "not an allowable number." }
like image 34
Joshua Pinter Avatar answered Sep 22 '22 13:09

Joshua Pinter