How to implement min / max validator in Rails 3?

What are rails for implementing the max max validation module in Rails 3?

I have a model with min_age and max_age attributes.

The age can be in the range 0..100, but I also want to check the intersection values, I mean that max is greater 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 
+52
validation ruby-on-rails-3
Dec 11 '10 at 10:27
source share
3 answers

Check ActiveModel :: Validations :: NumberericalityValidator: RailsAPI NumericalityValidator

Specification:

 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}") } 

the 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 check for availability or not, but you would just add this as another key to your checks, for example.

 validates :max_age, numericality: { less_than_or_equal_to: 100 }, presence: true 
+97
Jan 05 '11 at 19:36
source share

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

 validates :height, :inclusion => { :in => 1..3000, :message => "The height must be between 1 and 3000" } 
+27
Apr 12 '13 at 16:03
source share
 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, for example:

 validates_numericality_of :age, less_than_or_equal_to: 100, greater_than: 0 
+9
Jan 14 '14 at 14:19
source share



All Articles