<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
public class UserForm {
private String username;
private String password;
}
@Controller
public class UserController {
@PostMapping("/register")
public String registerUser(@Valid UserForm userForm, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "register";
}
return "redirect:/login";
}
}
html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
</head>
<body>
<form th:action="@{/register}" th:object="${userForm}" method="post">
<p>
<span th:if="${#fields.hasErrors('username')}" th:errors="*{username}"></span>
</p>
<p>
<span th:if="${#fields.hasErrors('password')}" th:errors="*{password}"></span>
</p>
<p>
</p>
</form>
</body>
</html>
properties
spring.messages.basename=validation
properties