CodexBloom - Programming Q&A Platform

Spring MVC: Can’t Resolve BindingResult Errors for Nested Objects in Form Submission

👀 Views: 338 💬 Answers: 1 📅 Created: 2025-07-02
spring-mvc validation bindingresult Java

I'm working through a tutorial and I've searched everywhere and can't find a clear answer. I'm integrating two systems and I'm working with an scenario with Spring MVC where I'm trying to bind a nested object from a form submission, but the `BindingResult` is not capturing validation errors properly. I'm using Spring 5.3.10 and have a form that submits a `User` object, which contains a nested `Address` object. Here's a simplified version of my model classes: ```java public class User { @NotEmpty(message = "Name want to be empty") private String name; @Valid private Address address; // getters and setters } public class Address { @NotEmpty(message = "Street want to be empty") private String street; private String city; // getters and setters } ``` In my controller, I'm handling the form submission like this: ```java @PostMapping("/submitUser") public String submitUser(@ModelAttribute User user, BindingResult bindingResult, Model model) { if (bindingResult.hasErrors()) { return "userForm"; // returns to the form with errors } // process user return "redirect:/success"; } ``` On the view side, I have a simple form: ```html <form action="/submitUser" method="post"> <input type="text" name="name" /> <input type="text" name="address.street" /> <input type="text" name="address.city" /> <button type="submit">Submit</button> </form> ``` When the form is submitted without filling in the required fields, I expect the `BindingResult` to contain errors for both `name` and `address.street`. However, I'm only getting errors for `name`, and the errors on the nested `Address` object are not being captured. I’ve tried adding the `@Valid` annotation to the `Address` field in the `User` class, and I’ve also ensured that the names in the form fields match the properties in the model. However, the validation for the nested object still fails to trigger. I am seeing the following output in the logs: ``` org.springframework.validation.FieldError: [address.street]: rejected value=[]; codes={NotEmpty.address.street,NotEmpty.street,NotEmpty}; arguments=[]; default message=Street want to be empty ``` It seems like the framework is aware of the validation behavior, but it doesn’t make its way into the `BindingResult`. Could someone point out what I might be missing or how I can properly capture these validation errors for nested objects in Spring MVC? This is my first time working with Java stable. Has anyone dealt with something similar?