Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails date validation with age

In my rails application there's a signup form which includes a DOB field.
The user's age need not to be more than 18.How can i give validation for this one.

My dob format is mm/dd/yy

like image 251
shajin Avatar asked Nov 29 '22 16:11

shajin


2 Answers

The syntax for this is pretty fun, you could 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 if it is before or after today.

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

like image 134
andrewmitchell Avatar answered Dec 06 '22 09:12

andrewmitchell


You can do the validation yourself. Convert the string to a date with to_date and check that it's less than 18.years.ago.

Put that check in a method in your user model, and have it call something like errors.add :dob, 'must be older than 18' if it fails.

Then at the top of your model call validates :dob_check

like image 35
B_. Avatar answered Dec 06 '22 09:12

B_.