簡體   English   中英

如何在同一域的多個字段中重用自定義驗證邏輯

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM