Validate that a value is in a certain range, e.g. 1 <= val <=2

Viewed 14429

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.

4 Answers

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"]
Related