[英]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'. 尽管如此,Grails仍会引发MissingPropertyException消息,消息为“无此类属性:class的notNullIfCustom ...可能的解决方案:notNullIfCustom”。 If I just copy and paste the closure body to each validator entry inside the constraints clause, it runs as expected.
如果仅将闭包主体复制并粘贴到constraints子句中的每个验证器条目,它将按预期运行。
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. PS:我不想使用共享验证器,因为我实际上不是在域类之间而是在同一域内的字段之间共享验证器。
The constraints
block is static, so your custom validators have to be too. constraints
块是静态的,因此您的自定义验证器也必须是静态的。 Just change that to 只需将其更改为
static notNullIfCustom = { val, object ->
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.