开发者

grails domain class validator + set unique constraint 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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜