jgg
jgg

Reputation: 1136

Spring MVC 3 nested object validation is failing with @Valid

I have following nested objects. I am using @Valid for validation in my controller. Here BindingResult object is not validating name field of Child object. Am I missing anything?

class Parent{
         @Valid  
         private Child child;
         //getter and setter for child object
 }

 class Child{
     @NotNull(messag="Name cannot be null")
     private String name;
     //getter and setter for name
 }

My controller validate method

@RequestMapping(value = "/validate", method = RequestMethod.POST)
public @ResponseBody  String validate(@Valid @ModelAttribute("parent") Parent parent, BindingResult bindingResult) {
    //Here I can see child name value if I say parent.getChild().getName()

  // But if  parent.getChild().getName() is null, bindingResult.hasErrors() is returning false

}

Upvotes: 4

Views: 3828

Answers (3)

jguilhermemv
jguilhermemv

Reputation: 779

You can't do it this way. You can't validate nested objects like that.

You have to use a validator.

Upvotes: 0

Hoàng Long
Hoàng Long

Reputation: 10848

As far as I know, @NotNull isn't quite right for String validation, since the Spring-model often mapping "no object received" to "blank string" instead.

Please try @NotBlank and sees if the BindingResults return errors.

Upvotes: 2

Japan Trivedi
Japan Trivedi

Reputation: 4483

I was also facing similar problem before sometime.

And after doing 2-3 days R&D I succeeded with validating nested object. I tried to do custom validations for the nested object.

You need to create a custom validator class and autowire it in the controller and in the method call validator.validate(parent, bindingResult) and it will return you the error binded with the nested object field in bindingResult object and then you can display it on jsp page as usual.

Hope this helps you. Cheers.

Upvotes: -1

Related Questions