DEV Community

Katie Radford
Katie Radford

Posted on

Validating age in Rails

Let's say you need to add a validation for the birthdate column so that the User's age is between 1 and 3 (must be a toddler).

In your User model:

validate :toddler_age

def toddler_age
  birthdate_within_range = ((4.years.ago - 1.day)..1.year.ago).cover?(birthdate)
  errors.add(:birthdate, 'must be 1-3 years old') unless birthdate_within_range
end
Enter fullscreen mode Exit fullscreen mode

Top comments (0)