【问题标题】:Custom domain constraint in grailsgrails中的自定义域约束
【发布时间】:2014-01-09 11:38:34
【问题描述】:
public class Service {

    String reviewChanges
    String comment

    static constraints = {
      reviewChanges (inList:['NO','YES'])
      comment validator: { val, obj ->
        if(reviewChanges=='YES') {
          (nullable:false, blank:false, minSize:1, maxSize:500)
        } else {
          (nullable:true, blank:true, minSize:1, maxSize:500)
        }
      }
    }
}

以上评论验证器对我不起作用。 我想如果 reviewChanges 字段选择 YES 那么 Comment 字段必须是 Mandatory 字段否则 Comment filed Non-Mandatory

【问题讨论】:

    标签: grails grails-orm grails-2.0 grails-domain-class


    【解决方案1】:

    使用自定义验证器的最佳方式是这样......

    static constraints = {
        reviewChanges(inList:['NO','YES'])
        comment validator: { val, obj,errors ->
            if (obj.reviewChanges == 'YES' && StringUtils.isEmpty(val))  { 
                errors.rejectValue('comment',"some.custom.validation.key")
            }
        }
    }
    

    errors.rejectValue 将允许您使用 propertyName 给出正确的字段错误,您也可以将其用于参数化错误...

    errors.rejectValue('propertyName','errorCode',errorArgs as Object[],'defaultMessage')
    

    并定义errorCode为message.properties来访问errorArgs之类的

    errorCode = This is {0} first parameter being passed as errorArgs.
    

    谢谢

    【讨论】:

      【解决方案2】:

      我认为你可以做这样的事情(我还没有测试过,但你明白了):

      static constraints = {
          reviewChanges(inList:['NO','YES'])
          comment validator: { val, obj ->
              if (obj.reviewChanges == 'YES' && StringUtils.isEmpty(val))  { 
                  return "some.custom.validation.key"
              }
          }
      }
      

      【讨论】:

      • 我怀疑可能必须是 obj.reviewChanges 而不仅仅是 reviewChanges。
      • 好地方,谢谢。我已经更新了答案。
      • 感谢您的回复 rcgeorge23 ​​但解决方案不起作用。我得到低于错误 98:期待 '}',发现 ':'@ 第 98 行,第 26 列。评论验证器:{ val,obj -> ^ 1 错误
      【解决方案3】:

      除非需要将 reviewChanges 作为字符串,否则我会将其设为 Boolean 字段并使用 Groovy 事实,您应该能够执行以下操作:

      class Service {
      
          Boolean reviewChanges
          String comment
      
          static constraints = {
             comment nullable:true, minSize:1, maxSize:500, validator: { val, obj ->
                if (obj.reviewChanges && (!val)){
                   return "comments.required"
                }
             }
          }
      

      }

      使用 Grails 2.3.3

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-11-27
        • 1970-01-01
        • 2019-06-13
        • 2014-08-23
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多