0
0

SpringBoot + Thymeleaf バリデーションエラーの表示

Last updated at Posted at 2024-08-24

記載内容

画面上の入力フォームにバリデーションエラーメッセージを表示させる際の実装方法について記述

Formクラス

UserForm.java
@Data
public class UserForm {

    @NotEmpty(message = "名前を入力してください")
    @Size(max = 100, message = "名前は100桁以内で入力してください")
    private String name;

    @Email
    private String email;

    @NotEmpty(message = "パスワードを入力してください")
    private String password;
}

Controller

UserController.java

@Controller
public class UserController {

  /**
   * ユーザー情報 Service
   */
  @Autowired
  private UserService userService;
  
    @GetMapping("/form")
    public String form(
        @ModelAttribute UserForm userForm,
        Model model
    ){
        return "user/form";
    }
    
    @PostMapping("/create")
    public String create(
        @ModelAttribute @Validated UserForm userForm,
        BindingResult result,
        Model model
    ) {
        if (result.hasErrors()) {
            // 入力チェックエラーの場合
            return "user/form";
        } else {
            // 新規ユーザ登録
            userService.create();
            return "redirect:/user/list";
        }
    }
}

Thymeleaf

user/form.html
    <form th:action="@{/create}" th:object="${userForm}" th:method="post">
    
        <label>名前</label>
        <input type="text" th:field="*{name}">

        <label>E-mail</label>
        <input type="text" th:field="*{email}">

        <label>パスワード</label>
        <input type="text" th:field="*{password}">

    </form>

エラーメッセージの表示方法

①まとめて表示する

formタグ配下に挿入
<li th:each="error : ${#fields.detailedErrors()}"
    class="text text-danger" th:text="${error.message}"></li>

・「#fields」には各フィールドのバリデーションチェックした結果が格納されている
・「detailedErrors」メソッドは、発生したエラーに関する情報をまとめて取得する

②各入力フィールドに表示する

入力項目「名前」にエラーメッセージを表示する場合
    <form th:action="@{/create}" th:object="${userForm}" th:method="post">
    
        <label>名前</label>
        <input type="text" th:field="*{name}" th:errorclass="err">
        <div th:if="${#fields.hasErrors('name')}" th:errors="*{name}" th:errorclass="err"></div>

・「th:errorclass」はエラーが起きたときに適用されるクラス名(テキストボックスを赤枠で囲むとか、メッセージを赤文字で表示させるなど)
・「hasErrors」は、引数に指定したフィールドのエラーが発生しているかを判断する
・「th:errors」は、バリデーションエラーがある場合に、指定された変数に関連するエラーメッセージを表示する。バリデーションエラーがない場合、何も表示されない。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0