无法在表单标签外显示验证消息

时间:2020-07-03 04:52:56

标签: java spring spring-mvc thymeleaf

我无法在form标签外显示验证消息。

我尝试过的

  • 确保返回值“ $ {#fields.errors('$ {office}')}”始终为假。
  • 确保输入值无效时发生字段错误。

源代码

控制器的一部分

 @PostMapping("/for_office/office_modify")
  public String updateOffice(
      Locale locale,
      Model model,
      RedirectAttributes attrs,
      @Valid @ModelAttribute Office office,
      BindingResult bindingResult)
      throws ParseException {
    attrs.addFlashAttribute("templateName", ViewNameConst.OFFICE_VIEW_NAME);
    if (bindingResult.hasErrors()) {
      logger.info("OfficeController:updateOffice:hasErrors");
      logger.info(bindingResult.toString());
      return ViewNameConst.OFFICE_VIEW_NAME;
    }
    ...
  }

胸腺模板的一部分

<ul class="errMsg text-danger"  th:if="${#fields.hasErrors('${office}')}">
  <li th:each="err : ${#fields.errors('${office}')}" th:text="${err}">
    Input is incorrect
  </li>
</ul>

2 个答案:

答案 0 :(得分:0)

我认为您的模板语法错误。 尝试针对所有错误显示此信息:

<div class="text-danger" th:if="${#fields.hasErrors('*')}">
    <p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>    
</div>

我不知道您的Office模型,但是您可以针对个别错误尝试以下方法:

<p th:if="${#fields.hasErrors('yourModelInstance.propertyName')}" 
 class="label label-danger" th:errors="*{yourModelInstance.propertyName}">Error here</p>

答案 1 :(得分:0)

我无法解决此问题,因此我解决了。我将错误消息放在了表单标签中。