如何在同一域的多个字段中重用自定义验证逻辑
How to reuse custom validation logic in multiple fields from the same Domain
我打算使用自定义验证器来检查域 class 中特定条件下的非空值。同一检查应 运行 在多个字段中。所以我 "factored" 验证闭包并尝试将其作为参数传递给约束子句中的每个验证器键。
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 [=10=] when type is custom"
}
尽管如此,Grails 会抛出消息 'No such property: notNullIfCustom for class... Possible solutions: notNullIfCustom' 的 MissingPropertyException。如果我只是将闭包主体复制并粘贴到约束子句中的每个验证器条目,它 运行 如预期的那样。
PS:我不想使用共享验证器,因为我实际上并没有在域 class 之间共享验证器,而是在同一域内的字段之间共享验证器。
constraints
块是静态的,因此您的自定义验证器也必须是静态的。只需将其更改为
static notNullIfCustom = { val, object ->
...
}
我打算使用自定义验证器来检查域 class 中特定条件下的非空值。同一检查应 运行 在多个字段中。所以我 "factored" 验证闭包并尝试将其作为参数传递给约束子句中的每个验证器键。
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 [=10=] when type is custom"
}
尽管如此,Grails 会抛出消息 'No such property: notNullIfCustom for class... Possible solutions: notNullIfCustom' 的 MissingPropertyException。如果我只是将闭包主体复制并粘贴到约束子句中的每个验证器条目,它 运行 如预期的那样。
PS:我不想使用共享验证器,因为我实际上并没有在域 class 之间共享验证器,而是在同一域内的字段之间共享验证器。
constraints
块是静态的,因此您的自定义验证器也必须是静态的。只需将其更改为
static notNullIfCustom = { val, object ->
...
}