![](/img/trans.png)
[英]Grails: how to return error message from controller logic (i.e. not originating from domain property validation)?
[英]How to reuse custom validation logic in multiple fields from the same Domain
我打算使用自定義驗證程序來檢查域類中特定條件下的非空值。 同一檢查應在多個字段中進行。 因此,我“構造了”驗證閉包,並嘗試將其作為參數傳遞給約束子句中的每個驗證器鍵。
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 ->
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.