Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC and JSR 303

I'm using Spring 3 and JSR 303. I have a form backing object whose nested objects need to be validated. In the example below, how do I validate formObject.getFoo().getBean()? When I run the code below, the result parameter is always empty, even if the HTML page submits nothing, when the validation should fail. Note that it works(i.e. the validation fails) when I validate it manually by calling validate(formObject.getFoo().getBean(), Bean.class).

@Controller
public class FormController {
    @RequestMapping(method = RequestMethod.POST)
    public void process(HttpServletRequest request, @Valid FormObject formObject, BindingResult result) {
            ...
    }

    // This is the class that needs to be validated.
    public class Bean {
        @NotBlank
        private String name;
    }

    public class Foo {
        private Bean bean;
    }

    public class FormObject {
        private Foo foo;
    }
}
like image 238
Tom Tucker Avatar asked Nov 15 '10 18:11

Tom Tucker


1 Answers

If you want validation to cascade down into a child object, then you must put the @Valid annotation on the field in the parent object:

public class Bean {
    @NotBlank
    private String name;
}

public class Foo {
    @Valid
    private Bean bean;
}

public class FormObject {
    @Valid
    private Foo foo;
}
like image 148
GaryF Avatar answered Sep 18 '22 23:09

GaryF