3

假设我有以下Foo对象:

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

我知道如何验证特定的约束:

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

我也知道如何一起放弃验证:

foo.save(validate: false)

但我不知道如何告诉 Grails 验证列表中的约束之外的所有约束。我可以创建一种方法来做我想做的事,但我想确保首先没有 Groovy 方法来做它。

更新

如果没有“groovier”方式,这就是我将如何做到这一点。

    // 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
    }
4

2 回答 2

9

考虑以下Foo域类

class Foo {
    String foo
    String bar
    String baz

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

baz可以排除验证,如下所示:

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

没有直接的方法可以发送排除字段列表进行验证。

于 2013-08-22T00:38:51.477 回答
0

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

于 2013-08-21T23:50:25.167 回答