4

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

shajin
  • 3,214
  • 5
  • 38
  • 53

2 Answers2

13

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

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
andrewmitchell
  • 1,559
  • 13
  • 15
8

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

B_.
  • 2,164
  • 2
  • 17
  • 20