SpringBoot バリデーション

SpringBootのバリデータを試す

・@NotBlank付与

import java.io.Serializable;
import javax.validation.constraints.NotBlank;

public class User implements Serializable {
    
    private static final long serialVersionUID = 1L;

    @NotBlank
    private String name;

    @NotBlank
    private String password;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

・バリデータのメッセージを設定

// src/main/resources/ValidationMessages.properties
javax.validation.constraints.NotBlank.message        = 入力してください。

・@Valid付与、BindingResultもセットで必要

    @RequestMapping(value="/", method=RequestMethod.GET)
    public ModelAndView index(ModelAndView mv) {
        mv.addObject("user", new User());
        mv.setViewName("index");
        return mv;
    }

    @RequestMapping(value="/regist", method=RequestMethod.POST)
    public ModelAndView regist(@ModelAttribute @Valid User user, BindingResult result, ModelAndView mv) {
        if (result.hasErrors()) {
            mv.setViewName("index");
            mv.addObject("user", user);
            return mv;
        }

        mv.setViewName("result");
        mv.addObject("user", user);
        return mv;
    }

・バリデーションメッセージの表示制御

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <form method="post" action="regist" th:object="${user}" >
        <label for="name">名前:</label>
        <input type="text" name="name" th:field="*{name}" th:errorclass="error-field">
        <span th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></span><br>
        <label for="password">パスワード:</label>
        <input type="text" name="password" th:field="*{password}" th:errorclass="error-field">
        <span th:if="${#fields.hasErrors('password')}" th:errors="password"></span>
        <input type="submit" value="送信" />
    </form>
</body>
</html>