在列表上使用自定义验证器

时间:2013-06-09 21:42:38

标签: grails customvalidator

我有一个Command对象如下:

class TestCreationCommand {

    String title    
    List testItems = [].withLazyDefault {new VocabQuestion()}

    static constraints = {
        title(blank:false,maxLength:150)

        testItems( validator: { ti ->
            ti.each {it.validate()}
        } )
    }
}

Test Items是VocabQuestion对象的列表。 VocabQuestion如下:

class VocabQuestion {

    static constraints = {
        question(blank:false,maxLength:150)
        answer(blank:false,maxLength:40)
    }

    static belongsTo = [vocabularyTest: VocabularyTest]

    String question
    String answer

}

我正在尝试使用自定义vaildator验证VocabQuestion上的约束(在上面的Command类的约束中),但我不断收到以下错误消息。

Return value from validation closure [validator] of property [testItems] of class [class vocabularytest.TestCreationCommand] is returning a list but the first element must be a string containing the error message code

我有许多不同的尝试......

我不确定该消息告诉我什么或如何调试闭包的返回值是什么。

任何人都可以提供任何指示吗?

2 个答案:

答案 0 :(得分:0)

你没有回到Grails的理解。你不能期望只返回任何东西,并让Grails知道如何处理它。返回布尔值或错误字符串。

static constraints = {
        title(blank:false,maxLength:150)

        testItems( validator: { ti ->
            Boolean errorExists = false
            ti.each {
               if (!it.validate()) {
                 errorExists = true
               }
            }
            errorExists
        })
    }

答案 1 :(得分:0)

查看此SO question它可能是您需要的验证器格式。

.every将返回一个布尔值。

相关问题