Grails min constraint for date validation
Asked Answered
H

1

9

I am a newbie in grails and groovy. I have a Project domain-class with start and end date. I want to put in a constraint specifying that the end date needs to be greater than the start date(and then further another child object of project needs to have its startdate and enddate validate with the parent Project's dates). Is this possible with the min constraint or do I have to put it elsewhere? Unique constraint does allow two properties to be linked that way, hoping min/max constraints allow that. I have tried

startDate(blank:false)
endDate(blank:false, min:'startDate')

It throws an error saying the property startDate is not available on Project

Harrisharrisburg answered 2/11, 2010 at 18:58 Comment(3)
My answer is assuming that endDate is defined as a java.util.Date. Is this correct? If not, please specify what it is and I'll update my answer accordingly.Extensor
Yes its a regular date. Was hoping the min constraint would apply to that too..Thanks for the answer :) So, min applies to integers only, right?Harrisharrisburg
Well, min can apply just fine to Date values. However, I don't believe you can use a dynamic value (i.e. another field value) in your constraint definition for min since constraints is a static closure. You could do endDate(min: new Date()), though, with no problems.Extensor
E
15

Try using a custom validator:

static constraints = {
    endDate(validator: { val, obj ->
        val?.after(obj.startDate)
    })
}

val is the value of the field and obj is a reference to the object being validated. The closure can contain whatever logic you need, so you can extend your validation in the way you're describing in your question (by accessing the child objects you refer to using obj).

The custom validator is pretty flexible. Have a look at the documentation. Ideally you'll want to return a custom message; how to do that can also be found in the docs linked above.

Extensor answered 2/11, 2010 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.