grails验证嵌套的命令对象不工作 [英] grails validate nested command object not working

查看:147
本文介绍了grails验证嵌套的命令对象不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用grails 2.2.1并尝试验证嵌套的命令结构。以下是我的命令对象的简化版本:

I'm using grails 2.2.1 and attempting to validate a nested command structure. Here is a simplified version of my command objects:

@Validateable
class SurveyCommand {

    SectionCommand useful
    SectionCommand recommend

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

@Validateable
class SectionCommand {
    String question
    String answer
    boolean isRequired

    static constraints = {
        answer(validator: answerNotBlank, nullable: true)
    }

    static answerNotBlank = { String val, SectionCommand obj ->
        if(obj.isRequired) {
            return val != null && !val.isEmpty()
        }
    }
}

当我尝试验证 SurveyCommand 的一个实例时,它总是返回 true ,无论段落值和我的自定义验证器位于 SectionCommand answerNotBlank )永远不会被调用。从grails文档看来,支持这种嵌套结构 deepValidate 默认为true)。但是,也许这个规则只适用于域对象而不是Command对象?或者我只是在这里缺少一些东西?

When I try to validate an instance of SurveyCommand it always returns true no matter the section values and my custom validator in SectionCommand (answerNotBlank) is never called. From the grails documentation, it seems that this kind of nested structure is supported (deepValidate defaults to true). However, maybe this rule only applies to domain objects and not Command objects? Or am I just missing something here?

推荐答案

您可以将自定义验证器添加到主要命令对象中。
$ b

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

这篇关于grails验证嵌套的命令对象不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆