How can I externalize a custom constraint in Grails?
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)
The closure has 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 )
}
精彩评论