【问题标题】:Grails validation using standard validators in custom validator在自定义验证器中使用标准验证器进行 Grails 验证
【发布时间】:2016-02-10 16:08:22
【问题描述】:

我想在自定义验证器中使用标准验证器。

我想确保仅当 model_type.has_range_options 为 false 时,人口和产品字段组合是唯一的。我尝试了以下方法,但它不起作用:

static constraints = {
    client validator: {val, obj, errors ->
        if (!obj.model_type?.has_range_options?.booleanValue()) {
            unique: ['population', 'product'] 
        }
    }
}

还有什么我可以尝试的吗?

【问题讨论】:

    标签: grails grails-orm grails-validation


    【解决方案1】:

    我刚刚写了自己独特的验证:

        static constraints = {
                client validator: {val, obj, errors ->
            if (this.findByPopulationAndClient(obj.population, obj.client) && !obj.model_type?.has_range_options?.booleanValue()) {
                errors.rejectValue('client', 'unique', "Population and Client must be unique")
            }
        }
    

    【讨论】:

      【解决方案2】:

      这是一个有趣的问题。过去,我求助于编写自己的内置约束版本,我想像你一样使用。

      我还没有弄清楚如何使用唯一约束来做到这一点,因为它作为持久约束的工作方式似乎有点不同。但是,对于大多数约束,您可以像这个空白约束一样使用它们,例如:

      static constraints = {
          client validator: { val, obj, errors ->
              def constraint = new org.grails.validation.BlankConstraint(propertyName: 'client', parameter: true, owningClass: this)
              constraint.validate(obj, val, errors)
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2013-08-18
        • 2019-07-17
        • 2015-03-28
        • 2015-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多