0

I'm trying to set dateOfBirth on register to be a minimum of 13 years old. I don't want to have an age field on my User class, I want to just stick with dateOfBirth.

How do I include validation to subtract exactly 13 years, accounting for leap years.

Currently in my constraints I am using this line:

dateOfBirth blank: false, max: (new Date() - 13*365)

I would prefer not to use custom validation as I believe there must be a way without it. I've tried the following:

dateOfBirth blank: false, use(TimeCategory) { max: new Date() - 13.year }

  • This doesn't work due to the use(TimeCategory) part (I believe)

I've also tried to use the magic numbers plugin to no avail. I tried:

dateOfBirth blank: false, max: 13.years.ago

and

dateOfBirth blank: false, max: 13.years.ago.toDate()

and imported com.metasieve.magicnumbers.* package.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Jonathan Airey
  • 416
  • 1
  • 5
  • 17

2 Answers2

2

What's wrong with custom validators? I believe this is an excellent case where a custom validator is the right choice.

import groovy.time.TimeCategory    

dateOfBirth validator: {
    use (TimeCategory) {
        it?.before(13.years.ago) 
    }
}
Kimi
  • 6,239
  • 5
  • 32
  • 49
0

The fact that your first try works (though inexactly) leads me to believe that this would work:

dateOfBirth blank: false, max: ((new Date()).toCalendar().add( -13, Calendar.YEAR )).getTime()

Though I would check that this isn't actually compiled to a single date, but is recomputed every time the constraint is checked.

billjamesdev
  • 14,554
  • 6
  • 53
  • 76