开发者

grails domain class validator + set unique constraint according to field values?

开发者 https://www.devze.com 2023-01-16 16:16 出处:网络
Is there a way to write a custom validator that will perform different validations according to field values?

Is there a way to write a custom validator that will perform different validations according to field values?

For example

class myModel{

   A a;
   B b;
   String prop
   static belongsTo:[m:myModel]

   constraints{
       prop(validator:{
          val,obj->
                if (obj.a== null){
                  unique:[b,prop]
                }
                else{
                  unique:[a,b,prop]
     开发者_StackOverflow社区           }
        })
   }
}

I'm quite confused about this.

Thanks in advance


While not the most elegant solution, this should work:

static constraints = {
    prop(validator: { val, obj ->
        if(obj.a == null) {
            return !myModel.findWhere(b: obj.b, prop: val)
        } else {
            return !myModel.findWhere(a: obj.a, b: obj.b, prop: val)
        }
    })
}

I don't believe there's a way to conditionally validate uniqueness based on property values without manually performing the query.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号