简体   繁体   中英

How to reuse custom validation logic in multiple fields from the same Domain

I intend to use a custom validator to check for not null values in specific conditions in a domain class. The same check should run in more than one field. So I "factored" the validation closure and tried to pass it as a parameter to each validator key in the constraints clause.

String type
String description
String size

static constraints = {
    description(nullable:true, validator: notNullIfCustom)
    size(nullable:true, validator: notNullIfCustom)
}

def notNullIfCustom = { val, object ->
        if (object.type == 'custom' && ! val)
            return "must provide a value to field ${0} when type is custom"
}

Nevertheless, Grails throws a MissingPropertyException with the message 'No such property: notNullIfCustom for class... Possible solutions: notNullIfCustom'. If I just copy and paste the closure body to each validator entry inside the constraints clause, it runs as expected.

PS: I don't want to use a shared validator because I'm not actually sharing the validator between domain classes, but between fields within the same domain.

The constraints block is static, so your custom validators have to be too. Just change that to

static notNullIfCustom = { val, object ->
   ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM