Home > AI > Backend > SpringBoot > spring-boot-starter-validation >

check validation example

Demo12Application.java

@SpringBootApplication
public class Demo12Application {

	public static void main(String[] args) {

        Person u = new Person("a", 18);
        System.out.println(u);
		SpringApplication.run(Demo12Application.class, args);
	}


}


@Data
@AllArgsConstructor
class Person {

    @NotNull
    @Size(min=2, max=30)
    private String name;

    @NotNull
    @Min(18)
    private Integer age;

}



@Controller
class PersonMCVConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/results").setViewName("results");
    }

    @GetMapping("/")
    public String show(Person person) {
        return "form";
    }

    @PostMapping("/")
    public String checkPersonInfo(@Valid Person person, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return "form";
        }

        return "redirect:/results";
    }
}

resources / form.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<form action="#" th:action="@{/}" th:object="${person}" method="post">
    <table>
        <tr>
            <td>Name:</td>
            <td><input type="text" th:field="*{name}" /></td>
            <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td>
        </tr>
        <tr>
            <td>Age:</td>
            <td><input type="text" th:field="*{age}" /></td>
            <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td>
        </tr>
        <tr>
            <td><button type="submit">Submit</button></td>
        </tr>
    </table>
</form>
</body>
</html>

resources / results.html

<html>
<body>
Congratulations! You are old enough to sign up for this site.
</body>
</html>

run the application to see /form and results

Leave a Reply