Reputation: 45646
I want to validate a number :value
to be within 1 or 2
validates :value, :format => { :with => /1|2/, :message => "Select number.." }
However, the above code is failing the validation when value == 1
Please ensure that your solution allows me to add a message for the validation.
Upvotes: 24
Views: 15278
Reputation: 18819
If you use inclusion
error messages are not good:
["Value is not included in the list"]
Use
validates :value, presence: true, numericality: { greater_than_or_equal_to: 1, less_than_or_equal_to: 10 }
For better error messages, like:
["Value must be less than or equal to 2"]
Upvotes: 4
Reputation: 7803
if you want it to be a number within 1 and 2 ( 1.5, 1.6839749, etc ) do
validates_numericality_of :value, :greater_than_or_equal_to => 1, :less_than_or_equal_to => 2, :message => "blah"
may not be what you are looking for but is worth noting,
Upvotes: 15
Reputation: 6983
You're looking for validates_inclusion_of:
validates_inclusion_of :value, :in => [1, 2],
:message => "Select one of %{value}"
You can also use the (fairly new) shothand form and a Range instead of an Array:
validates :value, :inclusion => { :in => 1..2 }
Upvotes: 18
Reputation: 20125
validates :value, :inclusion => {:in => [1,2]}
See http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_inclusion_of
Upvotes: 36