How to register a custom constraint

475 views Asked by At

I've created a custom constraint (most code copied from NullableConstraint) that I'd like to use in my project.

How do I register this new constraint so I can use it in my domain classes and command objects? I've tried following this answer but that didn't work. I also tried copying the code from here but that didn't work either.

2

There are 2 answers

1
Andrew Kretzer On

In your Config.groovy add the follow:

grails.gorm.default.constraints = {
    validMobilePhone(validator: { value, obj, errors ->
        if (!value) return

        value = PhoneNumberUtils.sanitizeNumber(value)

        if (!PhoneNumberUtils.validateMobilePhone(value)) {
            errors.rejectValue('mobilePhone', "invalid")
        }
    })

    nonNegative(min: new BigDecimal(0))

}

And then use this constraint in your domain:

static constraints = {
    value shared: 'nonNegative'
}
0
Majin Tenshi On

I set up a few custom Constraint classes in a Grails 3 project and carried them forward to Grails 4.

In my Application class, I register the custom constraints to 2 constraint registries. There are a few methods on the Application class you can choose from to implement this. I don't know if my selection was the best.

void doWithDynamicMethods(){
    //for domains
    applicationContext.getBean(
        org.grails.datastore.mapping.validation.ValidatorRegistry
    ).addConstraintFactory( someConstraintFactory )
    
    //for command objects
    (
        (DefaultConstraintEvaluator)
        applicationContext.getBean(
            org.grails.datastore.gorm.validation.constraints.eval.ConstraintsEvaluator
        )
    ).constraintRegistry.addConstraintFactory( someConstraintFactory )
}