我正在使用grails 2.2.1并尝试验证嵌套的命令结构。这是我的命令对象的简化版本:
@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文档中看来,this kind of nested structure is supported(deepValidate
默认为true)。但是,也许此规则仅适用于域对象,而不适用于Command对象?还是我只是在这里想念东西?
最佳答案
您可以在主命令对象中添加自定义验证器
@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 - grails验证嵌套的命令对象不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16181599/