How to implement min/max validator in Rails 3?

ValidationRuby on-Rails-3

Validation Problem Overview


What is the rails way of implementing a min max validator in Rails 3 ?

I have a model, with min_age and max_age attributes.

Age can be in the range of 0..100, but I want also to validate crossing values, I mean that max is greather than or equal to min

{:min_age => 0, :max_age => 0} => true
{:min_age => 0, :max_age => 1} => true
{:min_age => 1, :max_age => 0} => false # max < min
{:min_age => 1, :max_age => 101} => false # out of 0..100 range

Validation Solutions


Solution 1 - Validation

Check out the ActiveModel::Validations::NumericalityValidator: RailsAPI NumericalityValidator

spec:

it {
  subject.max_age = 10
  subject.min_age = 20
  subject.should be_invalid
  subject.errors[:min_age].should include("must be less than or equal to #{subject.max_age}")
}

code:

validates :min_age, numericality: { greater_than: 0, less_than_or_equal_to: :max_age }

validates :max_age, numericality: { less_than_or_equal_to: 100 }

I don't know if you want to validate presence or not, but you would just add that as another key to your validations, e.g.

validates :max_age, numericality: { less_than_or_equal_to: 100 }, presence: true

Solution 2 - Validation

You can also use inclusion...in, as in:

validates :height, inclusion: { in: 1..3000, message: 'The height must be between 1 and 3000' }

Solution 3 - Validation

validates_numericality_of :min_age, greater_than: 0
validates_numericality_of :max_age, less_than_or_equal_to: 100
validates_numericality_of :max_age, greater_than: :min_age

You can also use age, like this:

validates_numericality_of :age, less_than_or_equal_to: 100, greater_than: 0

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionastropanicView Question on Stackoverflow
Solution 1 - ValidationraybanView Answer on Stackoverflow
Solution 2 - Validationuser456584View Answer on Stackoverflow
Solution 3 - ValidationEastsideDevView Answer on Stackoverflow