You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Grails中使用自定义验证器实现某字段值作为另一字段校验约束

实现方案

直接在item字段的约束中添加自定义验证器即可,Grails的域类字段验证器闭包支持访问当前实例的所有字段,刚好适配你的场景。

修改后的完整域类代码

class Report {

    /* fields */
    String product
    String item


    static constraints = {
       product(nullable:true, inList:list)
       item(nullable:true, validator: { val, obj ->
           // 当product取值为'y'时,校验item不能为null/空字符串
           if (obj.product == 'y') {
               return val?.trim() ? true : ['requiredWhenProductY']
           }
           // 其他情况走默认的nullable约束
           return true
       })
    }
    static List list =['y', 'n', 'tbd']
}

可选配置:自定义错误提示

如果需要友好的校验错误提示,可在项目的messages.properties文件中添加如下配置:

Report.item.requiredWhenProductY=当product字段值为'y'时,item字段不允许为空

内容的提问来源于stack exchange,提问作者Dani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 17:45:08