繁体   English   中英

通过 Thymeleaf 实现字段验证(从 Freemarker 迁移到 Thymeleaf)

[英]Implement field validation via Thymeleaf (migrate from Freemarker to Thymeleaf)

我正在开发一个带有用户登录和注册的小型 Spring Boot 应用程序。 我想通过现场验证实现我自己的注册系统。 为了验证,我在控制器中使用我自己的org.springframework.validation.Validator Vaidator地捕捉所有的错误bindingResult在控制器并将其发送到前端在model领域:

@PostMapping("/registration")
    public String signUpUser(User userForm, BindingResult bindingResult,
                             Model model) {
        validator.validate(userForm, bindingResult);

        if(bindingResult.hasErrors()) {
            Map<String, String> errors = ControllerUtils.getFieldErrors(bindingResult);
            model.mergeAttributes(errors);
            return "registration";
        }
        return "registration";

如果有任何验证错误, Map<String, String> errors将包含所有Map<String, String> errors 例如,如果用户在注册时不填写字段firstName映射将持有对象,如: "firstNameError" -> "Please, fill the field" ,依此类推。

在我之前的项目中,我使用 Freemarker 作为模板引擎,并且某些元素的前端代码如下所示:

 <label for="inputFirstName" class="sr-only">First Name</label>
    <input type="text" name="firstName" id="inputFirstName"
           class="form-control ${(firstNameError??)?string('is-invalid','')}"
           placeholder="First Name" required autofocus>
    <div class="text-left invalid-feedback m-1 ml-1">
        <#if (firstNameError)??>
            ${firstNameError}
        </#if>
    </div>

因此,当我的用户名出错时 - 我的输入将 class 更改为class="form control is-invalid"并突出显示有错误的字段,然后在 div 中显示一条错误消息

现在我使用 Thymeleaf 作为模板引擎。 要显示我使用的错误文本

<div th:if="${firstNameError}" class="invalid-feedback">
        <a th:text="${firstNameError}"></a>
    </div>

但是如何更改<input...动态class以突出显示有错误的恶魔?

谢谢!

您可以像这样使用 thymeleaf classappend th:classappend

<input type="text" name="firstName" id="inputFirstName" th:classappend="${condition} ? conditionTrueClass : conditionFalseClass "/>

请看这个答案

您需要在类中使用条件语句来评估它是否应该使用“错误类”

例子:

<p  th:if="${#fields.hasErrors('age')}" th:class="${#fields.hasErrors('age')}? error">Invalid Age</p>

<style>
    .error {
        color: red;
    }
</style>

另一个 Thymeleaf 属性 th:errors 使我们能够在指定的选择器上显示所有错误,比如电子邮件:

<div>
    <label for="email">Email</label> <input type="text" th:field="*{email}" />
    <p th:if="${#fields.hasErrors('email')}" th:errorclass="error" th:errors="*{email}" />
</div>

参考: https : //www.baeldung.com/spring-thymeleaf-error-messages

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM