Search code examples
grailsgrails3.2.0

Register custom constraints


I'm trying to upgrade Grails 2.3.7 project to Grails 3.2.3. In 2.3.7, I used custom constraints and register them in /conf/Config.groovy using:

org.codehaus.groovy.grails.validation.ConstrainedProperty.registerNewConstraint('description', my.validation.DescriptionConstraint)

Then I can use something like this in domain:

static constraints = {
  approvedDate(description: '>= applyDate')
}

However, in Grails 3.2.3, When I put above command (and remove org.codehaus.groovy from package name) in /conf/application.groovy I got following error:

Error occurred running Grails CLI: No signature of method: groovy.util.ConfigObject.registerNewConstraint() is applicable for argument types: (groovy.util.ConfigObject, groovy.util.ConfigObject) values: [[:], [DESCRIPTION_CONSTRAINT:[:]]]

I've notice that validation class is somewhat changed in Grails 3. However using constraint class from Grails-validation still got the same error.

All validation plugins I found were long abandoned before Grails 3. And I can't find any document for register new constraint in Grails 3.2.


Solution

  • Calling ConstrainedProperty.registerNewConstraint in /grails-app/init/BootStrap.groovy works. (tested with Grails 3.2.4)

    class BootStrap {
      def init = { servletContext ->
        grails.validation.ConstrainedProperty.registerNewConstraint('description', my.validation.DescriptionConstraint)
        // The rest of bootstrap code
      }
    }
    

    Note. Previously, I call it from main() in /grails-app/init/Application.groovy. It works for running application. However, it does not work with integration test.