tags:

views:

29

answers:

1

I'd like to keep my custom constraint validator closures outside of the constraints definition for my attribute because it makes it easier to read and reuse, but I'm doing something wrong. I'm trying to do this:

class City {
    String name

    static constraints = {
        name( nullable:false, blank:false, validator: uniqueCityValidator )
    }

    def uniqueCityValidator = {
        if ( City.findByNameILike(it) ) return ['cityExists']
    }
}

But I'm getting the following error:

groovy.lang.MissingPropertyException: No such property: uniqueCityValidator for class: com.xxx.City
at com.withfriends.City$__clinit__closure2.doCall(City.groovy:7)
at com.withfriends.City$__clinit__closure2.doCall(City.groovy)
at grails.test.MockUtils.addValidateMethod(MockUtils.groovy:857)
at grails.test.MockUtils.prepareForConstraintsTests(MockUtils.groovy:544)
at grails.test.MockUtils$prepareForConstraintsTests.call(Unknown Source)
at grails.test.GrailsUnitTestCase.mockForConstraintsTests(GrailsUnitTestCase.groovy:116)
at com.xxx.CityTests.testUniqueConstraintForSameCase(CityTests.groovy:9)
+3  A: 

The closure have to be static:

static uniqueCityValidator = {
    if ( City.findByNameILike(it) ) return ['cityExists']
}

We have something similar. In our project we have the custom constraints in an own class. So we can use them in every domain class. The code looks like:

class Validation {
    static uniqueCityValidator = {
        if ( City.findByNameILike(it) ) return ['cityExists']
    }
}

In the domain class:

static constraints = {
    name( nullable:false, blank:false, validator: Validation.uniqueCityValidator )
}
Daniel Engmann
Excellent, thanks!
Javid Jamae