ubiquibacon
ubiquibacon

Reputation: 10677

How to skip validation of specific constraints?

Assume I have the following Foo object:

Foo foo = new Foo(foo: "foo", bar: "bar", baz: "baz")

I know how to validation specific constraints:

foo.validate(["foo", "bar"]) // validates the "foo" property and the "bar" property, but not the "baz" property

I also know how to forego validation all together:

foo.save(validate: false)

But I don't know how to tell Grails to validate all constraints except those in a list. I could make a method that does what I want, but I wanted to make sure there wasn't a Groovy way to do it first.

Update

Here is how I will do this if there isn't a "groovier" way.

    // This method exists in my Util.groovy class in my src/groovy folder
    static def validateWithBlacklistAndSave(def obj, def blacklist = null) {
        def propertiesToValidate = obj.domainClass.constraints.keySet().collectMany{ !blacklist?.contains(it)?  [it] : [] }
        if(obj.validate(propertiesToValidate)) {
            obj.save(flush: true, validate: false)
        }
        obj
    }

Upvotes: 3

Views: 4832

Answers (2)

dmahapatro
dmahapatro

Reputation: 50275

Considering the below Foo domain class

class Foo {
    String foo
    String bar
    String baz

    static constraints = {
        foo size: 4..7
        bar size: 4..7
        baz size: 4..7
    }
}

Validation for baz can be excluded as follows:

Foo foo = new Foo(foo: "fool", bar: "bars", baz: "baz")

//Gather all fields
def allFields = foo.class.declaredFields
                         .collectMany{!it.synthetic ? [it.name] : []}
//Gather excluded fields
def excludedFields = ['baz'] //Add other fields if necessary

//All but excluded fields
def allButExcluded = allFields - excludedFields

assert foo.validate(allButExcluded)
assert foo.save(validate: false) //without validate: false, validation kicks in
assert !foo.errors.allErrors

There is no direct way to send a list of excluded fields for validation.

Upvotes: 9

Anatoly
Anatoly

Reputation: 456

You can define customized constraints maps, which you can then effectively filter from either supporting command classes or Config.groovy via exclude parameter.

Upvotes: 0

Related Questions