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 -
  errors.add(:birthdate, 'must be 1-3 years old') unless birthdate_within_range
Enter fullscreen mode Exit fullscreen mode

Top comments (0)