Grails validates invalid command nested object

I am using grails 2.2.1 and trying to check the nested command structure. Here is a simplified version of my team 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()
        }
    }
}

When I try to validate an instance SurveyCommand, it always returns trueregardless of the value of the section, and my custom validator in SectionCommand( answerNotBlank) is never called. From the grails documentation, it seems that such a nested structure is supported ( deepValidatedefaults to true). However, perhaps this rule applies only to domain objects, and not to commands? Or am I just missing something here?

+5
source share
3 answers

@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)
    }
}
+4

Grails 2.3 , Cascade Validation Plugin . , cascade, , . :

class SurveyCommand {
    ...

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

validation unit, mockForConstraintsTest(), command Config.groovy @Validateable - Grails. . .

validateable, , Config.groovy

grails.validateable.classes = 
           [yourpackage.SurveyCommand, yourpackage.SectionCommand] 
+2

All Articles