Rails 6.1 adds support for validating numeric values fall in a range using `in:` option

To validate a numerical value that should fall within a specific range, the numericality validation helper provides us with options such as :greater_than_or_equal_to and :less_than_or_equal_to or, :greater_than and :less_than. This is easy to understand as we know what kind of validation is expected just by reading the expressive option names.

But wouldn’t it be great if there was a way that could help save some key strokes while at the same time not compromise on the simplicity and expressiveness of the code?

In the latest update to Rails, this has been addressed. We can now use the in: option that accepts a range of values we wish to validate against.

We have always used ranges in Ruby. This is what a range looks like -

range = (1..5)
range.each { |n| puts n }        # => 1, 2, 3, 4, 5

So, let’s say for profile details, we want a user to input their age and we want it to be between 18 and 65.

Before

The way to achieve this would have been,

class User < ApplicationRecord
  validates :age, numericality: { greater_than_or_equal_to: 18, less_than_or_equal_to: 65 }
end

After

Now, the same can be achieved using the in: option like so,

class User < ApplicationRecord
  validates :age, numericality: { in: 18..65 }
end

When we try to add a User with an age value that does not fall in between 18 and 65, this is what we get -

User.create!(name: "Chris", age: 14)

# => ActiveRecord::RecordInvalid (Validation failed: Age must be greater than or equal to 18)

Need help on your Ruby on Rails or React project?

Join Our Newsletter