grails validate nested command object not working

我怕爱的太早我们不能终老 提交于 2019-12-05 08:17:25

You could add a custom validator to your main command object

@Validateable
class SurveyCommand {

    SectionCommand useful
    SectionCommand recommend

    static subValidator = {val, obj ->
        return val.validate() ?: 'not.valid'
    }

    static constraints = {
        useful(validator: subValidator)
        recommend(validator: subValidator)
    }

    SurveyCommand() {
        useful = new SectionCommand(
            question: 'Did you find this useful?',
            isRequired: true)
        recommend = new SectionCommand(
            question: 'Would you recommend to someone else?',
            isRequired: false)
    }
}
jgibson

For Grails 2.3 and later I've found that the Cascade Validation Plugin solves this problem nicely. It defines a new validator type called cascade which does exactly what you'd expect. Once installed your example would become:

class SurveyCommand {
    ...

    static constraints = {
        useful(cascade: true)
        recommend(cascade: true)
    }
}
dmahapatro

If you are trying to test validation from unit tests using mockForConstraintsTest() then you should register the command objects inConfig.groovy instead of using @Validateable because of an existing Grails Bug. Refer this SO question/answers for details.

You can register the validateable class as below in Config.groovy

grails.validateable.classes = 
           [yourpackage.SurveyCommand, yourpackage.SectionCommand] 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!