Grails validation using standard validators in custom validator

90 Views Asked by At

I'd like to use a standard validator in a custom validator.

I want to ensure the population and product field combo is unique ONLY if the model_type.has_range_options is false. I've tried the following but it is not working:

static constraints = {
    client validator: {val, obj, errors ->
        if (!obj.model_type?.has_range_options?.booleanValue()) {
            unique: ['population', 'product'] 
        }
    }
}

Is there something else I could try?

2

There are 2 best solutions below

0
Todd M On

I just ended up writing my own unique validation:

    static constraints = {
            client validator: {val, obj, errors ->
        if (this.findByPopulationAndClient(obj.population, obj.client) && !obj.model_type?.has_range_options?.booleanValue()) {
            errors.rejectValue('client', 'unique', "Population and Client must be unique")
        }
    }
0
doelleri On

This is an interesting problem. In the past I've resorted to writing my own version of the built-in constraint I wanted to use like you have.

I haven't been able to figure out how to do this with the unique constraint yet since it seems to work a little differently as a persistent constraint. However, for most of the constraints you can use them like this blank constraint, for example:

static constraints = {
    client validator: { val, obj, errors ->
        def constraint = new org.grails.validation.BlankConstraint(propertyName: 'client', parameter: true, owningClass: this)
        constraint.validate(obj, val, errors)
    }
}