Spring Boot validation not working




Asked on October 06, 2023
I have a class with Jakarta @NotNull and @Size validation.

1)

public class Employee implements Serializable {

@NotNull

@Size(min = 5, max = 15)

private String empId;

@NotNull

@Size(min = 5, max = 20)

private String name;

}


2) In controller class:


@PostMapping("post-emp")

public ModelAndView createUser(@Valid Employee emp, BindingResult result) {

  ------

}


3) In Thymeleaf :

<form action="#" th:action="@{/post-emp}" th:object="${emp}" method="POST">

<label th:if="${#fields.hasErrors('empId')}" th:text="#{error.emp.id}" th:class="'error'">Id Error</label>

------

</form>


Validation is not working.





Replied on October 06, 2023
Check following points.

1. Need spring-boot-starter-validation dependency.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

2. Use @ModelAttribute with @Valid :

@PostMapping("post-emp")
public ModelAndView createUser(@Valid @ModelAttribute("emp") Employee user, BindingResult result) {
}




Replied on October 06, 2023
Thanks. Working.

Write Answer











©2024 concretepage.com | Privacy Policy | Contact Us