我打算使用自定义验证器来检查域类中特定条件下的非空值。同一检查应在多个字段中进行。因此,我“构造了”验证闭包,并尝试将其作为参数传递给约束子句中的每个验证器键。
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"
}
但是,Grails会抛出MissingPropertyException消息,消息为“没有此类属性:class ...的notNullIfCustom ...可能的解决方案:notNullIfCustom”。如果仅将闭包主体复制并粘贴到constraints子句中的每个验证器条目,它将按预期运行。
PS:我不想使用共享验证器,因为我实际上不是在域类之间而是在同一域内的字段之间共享验证器。
最佳答案
constraints
块是静态的,因此您的自定义验证器也必须是静态的。只需将其更改为
static notNullIfCustom = { val, object ->
...
}
关于grails - 如何在同一域的多个字段中重用自定义验证逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29874920/