I have two entities(java classes), User and Address in my spring MVC Thymeleaf app. User class contains a field of the Address class and refers to it. I have a Thymeleaf form which contains input elements to receive data for the User and Address entities. When I want to validate the form on submitting, no errors and no validation for the fields of the Address entity happen. But validation and displaying errors for the User entity work fine.
The User and Address entities:
@AllArgsConstructor
@NoArgsConstructor
@Data
public class User {
private String id;
@NotEmpty("Enter first name")
private String firstName;
@NotEmpty("Enter last name")
private String lastName;
private Address address;
}
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Address {
private String id;
@NotEmpty("Enter the city")
private String City;
private String Street;
}
Spring MVC controller:
@GetMapping("/getUserForm")
public String getUserForm(Model model)
{
User user= new User();
model.addAttribute("user", user);
return "userForm";
}
@PostMapping("/saveUser")
public String saveUser(@Valid @ModelAttribute("user") User user, BindingResult result, Model model)
{
if(result.hasErrors()) {
System.out.println("errrrrrrrrrrrrrrrrrrrrrr");
return "userForm";
}
}
Thymeleaf form:
<form th:method="post" th:action="@{/saveUser}" th:object="${user}" >
<input type="text" th:field="*{firstName}"/>
<p th:if="${#fields.hasErrors('firstName')}" th:errors="*{firstName}" />
<input type="text" th:field="*{lastName}"/>
<p th:if="${#fields.hasErrors('lastName')}" th:errors="*{lastName}" />
<input type="text" th:field="*{address.city}"/>
<p th:if="${#fields.hasErrors('address.city')}" th:errors="*{address.city}" />
<button type="submit">Save</button>
</form>
Thanks in advance for your help.
You need to annotate the address filed with @Valid. It works fine for nested classes.