Checking rails with age

My rails application has a registration form that includes a DOB field.
The age of the user should not be more than 18. How can I give confirmation for this.

My dob format is mm / dd / yy

+4
source share
2 answers

The syntax for this is pretty funny, you can do something like this:

old_enough = ("10/23/2000".to_date + 18.years) < Date.today 

Turn your string into a date, add 18 years and see not before or after today.

If you want to put this in a model validator, this railscast might be useful: http://railscasts.com/episodes/211-validations-in-rails-3

+12
source

You can perform the check yourself. Convert the string to a date using to_date and make sure it is less than 18.years.ago .

Put this check in your user model and call it as errors.add :dob, 'must be older than 18' if it does not work.

Then at the top of your validates :dob_check model call validates :dob_check

+8
source

All Articles