views:

25

answers:

1

Hi,

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]
                }
        })
   }
}

I'm quite confused about this.

Thanks in advance

+1  A: 

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.

Rob Hruska
Good answer. Also validations such as unique correspond to schema generation so trying to apply a condition to them is not possible AFAIK.
proflux