Skip to content

Add an option `in` for the numeric validation of the model attributes. #13675

wants to merge 1 commit into from

4 participants



I sent a message on the Core list without pertinent answers. Thus, this pull request will able to refactor this code:

class Person
  validates_numericality_of :age, greater_than_or_equal_to: 1, less_than_or_equal_to: 100


class Person
  validates_numericality_of :age, in: 1..100

Although, we can use validates_inclusion_of, It will be more consistent to define the same kind of options for one same attribute.


@GRoguelon GRoguelon Add an option `in` for the numeric validation of the model attributes.
Add the ability to provide a Range of Numeric values to define the limits of the interval of values allowed.
Ruby on Rails member

Hello @GRoguelon,

Sorry if I'm missing something but why:

validates :age, inclusion: 1..100

would not be sufficient ? If it's in here, it will be an integer anyway I guess.


Yes of course, you can use this way to do it but I think, it will be more concise, if we can use the power of Range in validates_numericality_of`.


Inclusion in an Array is not the same as inclusion in Range, if the set is an uncountable (or countable but very large, to the point where it's not efficient to convert to an Array and do an inclusion check). For example checking that a date is within a start and end date.

Could use a validation that makes use of the range's .cover method for this case.


My first attempt of implementation used .cover but the modification implied a lot of change in the code.

Ruby on Rails member

Thank you, but adding this option:

validates_numericality_of :age, in: 1..100

Doesn't seem to bring much improvement over the existing approach:

validates :age, numericality: true, inclusion: { in: 1..100 }

# or even
validates_numericality_of :age
validates_inclusion_of :age, in: 1..100

Plus the inclusion validator already gives you the required functionality and a reasonable error message for such validation, so adding more code on top of numericality to replicate such functionality is a no go.

As a side note, this has been already requested in #144, #8979, #11844 (and maybe some other), and already got rejected.

Thanks for your contribution.

@GRoguelon GRoguelon deleted the GRoguelon:validates_numericality_in_range branch Jan 23, 2014
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.