前提
バリデーションによるエラーメッセージが表示されない。
実現したいこと
バリデーションによるエラーメッセージの表示。
発生している問題・エラーメッセージ
Validation failed for object='productForm'. Error count: 1 org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'productForm' on field 'name': rejected value [null]; codes [NotNull.productForm.name,NotNull.name,NotNull.java.lang.String,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [productForm.name,name]; arguments []; default message [name]]; default message [製品名/単位を入力してください]
該当のソースコード
thymeleaf
1<h1 th:text="${title}">タイトル</h1> 2 <form th:action="@{/product/update}" method="post" th:object="${productForm}"> 3 <div class="mt-3"> 4 <label for="productInput" class="form-label">商品名/単位</label> 5 <input type="text" name="name" class="form-control" id="name" th:value="*{name}"> 6 <div class="text-danger mb-4" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></div> 7 </div> 8 <input th:if="${id}" type="hidden" name="id" th:value="${id}"> 9 <div class="text-center mt-3"> 10 <button type="submit" class="btn btn-primary">保存</button> 11 <a class="btn btn-secondary" th:href="@{/product/list}">キャンセル</a> 12 </div> 13 </form>
Controller
1@PostMapping("/update") 2 public String update( 3 @Validated @ModelAttribute ProductForm productForm, 4 @RequestParam("id") int id, 5 BindingResult result, 6 Model model, 7 RedirectAttributes redirectAttributes 8 ) { 9 10 if (result.hasErrors()) { 11 model.addAttribute("title", "商品情報 編集画面"); 12 model.addAttribute("productForm", productForm); 13 14 return "product/edit"; 15 } else { 16 Product product = makeProduct(productForm, id); 17 18 productService.update(product); 19 redirectAttributes.addFlashAttribute("complete", "変更が完了しました"); 20 21 return "redirect:/product/list"; 22 }
試したこと
ネット上で調べてみたのですが、解決に至りませんでした。
補足情報(FW/ツールのバージョンなど)
java11, spring boot2.7.0, thymeleaf
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。