4

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

}

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

You have to use a validator.

Comments

-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.