grailscommand-objectsgrails-constraints

Can one constraint on a command object check the result of another?


This is a simple example that doesn't work, I'm wondering if there is a way to validate a inside the validator block of b if it hasn't already been validated.

Example how I thought it would work:

static constraints =
{
    a nullable: false
    b validator: { val, obj ->
        if(obj.errors.hasFieldError('a'))
        {
            return false
        }
    }
}

Note: in this scenario obj.errors.hasFieldError('a') returns false even if a is null.


Solution

  • I don't think there's any guarantee of the order the constraints are checked, and it's unlikely that it would have anything to do with the order specified in the constraints block.

    However, in addition to the common one-arg custom validator that passes you the current value for that field and the two-arg validator you show where you also get access to the domain class instance, there's a three-arg variant (unfortunately it doesn't seem to be covered in the Grails reference docs ...) where the third argument is the Spring Errors instance. If you define a three-arg validator, GORM ignores any return value since it's assumed that you'll be working directly with the Errors instance, calling one or more of the different rejectValue methods yourself for any validation issues.

    So you could remove from the constraints block any standard validations that you want to run yourself and use this approach instead. You can find more information about working with the Errors object in the Spring docs.