【问题标题】:How to validate a form with thymeleaf and spring?如何使用 thymeleaf 和 spring 验证表单?
【发布时间】:2019-12-26 02:25:05
【问题描述】:

我只想验证表单数据并显示错误消息。验证电子邮件格式、密码大小和密码匹配。最好的方法是什么?

这是我尝试过的

我的控制器

@PostMapping("/{customerId}/createUser")
public String signIn(@PathVariable(value = "customerId", required = false) Long customerId,
        @ModelAttribute(name = "user") @Valid Users user, RedirectAttributes redirectAttributes,
        BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        return "customerNewUser";
    }

    // Encrypt password
    user.setPassword(encoder.encode(user.getPassword()));
    user.setCustomerId(customerId);
    user.setEventDescription("User Admin creation");

    try {
        Users returnedUser = userService.save(user);

        List<Authorities> authorities = new ArrayList<Authorities>();
        Authorities auth = new Authorities(new AuthoritiesPK(returnedUser.getId(), "ROLE_CLI_ADM"), returnedUser,
                "ROLE_CLI_ADM");
        authorities.add(auth);
        returnedUser.setAuthorities(authorities);
        returnedUser.setEventDescription("Add Admin role");

        for (int i = 0; i < returnedUser.getAuthorities().size(); i++) {
            authorityService.save(returnedUser.getAuthorities().get(i));
        }
        userService.save(returnedUser);
    } catch (WebExchangeBindException webe) {
        StringBuilder errorBuilder = new StringBuilder();
        for (ObjectError error : webe.getAllErrors()) {
            errorBuilder.append(messageSource.getMessage(error.getCode(), null, Locale.getDefault())).append("\n");
        }
        redirectAttributes.addFlashAttribute("signInError", errorBuilder.toString());
    }

    return "redirect:/customers/?id=" + customerId;
}

customerNewUser html 文件中的表单

<form
                        th:action="@{${user?.id} ? '/customers/' + ${customer.id} + '/createUser/' + ${user.id} : '/customers/' + ${customer.id} + '/createUser/'}"
                        th:object="${user}" action="#" method="post">

<div class="alert alert-danger" th:if="${#fields.hasAnyErrors()}">
                            <div th:each="detailedError : ${#fields.detailedErrors()}">
                                <span th:text="${detailedError.message}"></span>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="form-row">
                                <div class="col-md-5">
                                    <label class="text-right label-control"
                                        th:text="#{firstname} + ':'">Firstname:</label>
                                </div>
                                <div class="col-md-4">
                                    <input type="text" id="firstname" name="firstname"
                                        th:value="${user?.firstname} ? ${user?.firstname} : ''"
                                        class="form-control" th:placeholder="#{firstname}"
                                        required="required" autofocus="autofocus" th:field="*{firstname}"/>
                                        <label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('firstname')}" th:errors="*{firstname}" th:text="#{passwordError}">Password Error</label>
                                </div>
                            </div>
                            </div>
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="col-md-5">
                                        <label class="text-right label-control"
                                            th:text="#{surname} + ':'">Surname:</label>
                                    </div>
                                    <div class="col-md-4">
                                        <input type="text" id="surname" name="surname"
                                            th:value="${user?.surname} ? ${user?.surname} : ''"
                                            class="form-control" th:placeholder="#{surname}"
                                            autofocus="autofocus" />
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="form-row">
                                    <div class="col-md-5">
                                        <label class="text-right label-control"
                                            th:text="#{email} + ':'">Email:</label>
                                    </div>
                                    <div class="col-md-4">
                                        <input th:placeholder="#{email}" required="required"
                                            autofocus="autofocus" id="email" class="form-control"
                                            type="text" th:value="${user?.email} ? ${user?.email} : ''"
                                            name="email" th:field="*{email}"/>
                                            <label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('email')}" th:errors="*{email}" th:text="#{emailError}">Email Error</label>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group" th:if="!${user?.id}">
                                <div class="form-row">
                                    <div class="col-md-5">
                                        <label class="text-right label-control"
                                            th:text="#{password} + ':'">Password:</label>
                                    </div>
                                    <div class="col-md-4">
                                        <input type="password" id="password" name="password"
                                            class="form-control" th:placeholder="#{password}"
                                            required="required" autofocus="autofocus" th:field="*{password}"/>
                                            <label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('password')}" th:errors="*{password}" th:text="#{passwordError}">Password Error</label>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group" th:if="!${user?.id}">
                                <div class="form-row">
                                    <div class="col-md-5">
                                        <label class="text-right label-control"
                                            th:text="#{passwordConfirmation} + ':'">Password confirmation:</label>
                                    </div>
                                    <div class="col-md-4">
                                        <input type="password" id="matchPassword" name="matchPassword"
                                            class="form-control" th:placeholder="#{password}"
                                            required="required" autofocus="autofocus" th:field="*{matchPassword}"/>
                                            <label th:style="'color: red;'" class="text-right label-control" th:if="${#fields.hasErrors('matchPassword')}" th:errors="*{matchPassword}" th:text="#{matchPassword}">Match Password Error</label>
                                    </div>
                                </div>
                            </div>

                            <div class="form-group" th:if="${user?.id}">
                                <div class="form-row">
                                    <div class="col-md-5">
                                        <label class="text-right label-control"
                                            th:text="#{userStatus} + ':'">Status:</label>
                                    </div>
                                    <div class="col-md-3">
                                        <select class="form-control form-control" id="userStatus"
                                            name="userStatus">
                                            <option
                                                th:each="userStatus : ${T(br.com.macrosul.stetho.entity.UserStatus).values()}"
                                                th:text="${userStatus}" th:value="${userStatus}"
                                                th:selected="${user.userStatus} eq ${userStatus}"></option>
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="form-group">
                                <p class="error-control" th:text="${signInError}"></p>
                            </div>
                            <input type="submit" class="btn btn-md btn-block"
                                value="Sign in"
                                th:value="${user?.id} ? #{updateUser} : #{signIn}" />
                    </form>

这是我尝试强制输入密码大小错误时的堆栈跟踪 ->

 @Size(min=6)
@Column(nullable = false)
private String password;

字段“密码”上的对象“用户”中的字段错误:拒绝值 [12345];代码 [Size.user.password,Size.password,Size.java.lang.String,Size];参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [user.password,password];论据 [];默认消息 [密码],2147483647,6];默认消息 [tamanho deve estar entre 6 e 2147483647]

我想要一个简单的验证。如果有更简单的方法来指示用户数据无效,我将不胜感激任何帮助或建议!

【问题讨论】:

    标签: spring forms validation thymeleaf


    【解决方案1】:

    这有点晚了,但你需要把你的 BindingResult 放在你的 @valid 属性旁边,而不是:

    @ModelAttribute(name = "user") @Valid Users user, RedirectAttributes redirectAttributes, BindingResult bindingResult
    

    你应该写:

    @ModelAttribute(name = "user") @Valid Users user, BindingResult bindingResult, RedirectAttributes redirectAttributes
    

    【讨论】:

      【解决方案2】:

      您需要一个如下所示的验证器。它不是您需要的确切代码,但足够并且非常接近您需要的代码。

      @Override
          public void validate(Object o, Errors errors) {
           ValidationUtils.rejectIfEmptyOrWhitespace(errors, "useremail", "NotEmpty");
           ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userfirstname", "NotEmpty");
           ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userlastname", "NotEmpty");
           ValidationUtils.rejectIfEmptyOrWhitespace(errors, "useraddress", "NotEmpty");
      
           ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotEmpty");
              if (user.getPassword().length() < 8 || user.getPassword().length() > 32) {
              errors.rejectValue("password", "Size.userForm.password");
              }
      
              if (!user.getPasswordConfirm().equals(user.getPassword())) {
              errors.rejectValue("passwordConfirm", "Diff.userForm.passwordConfirm");
              }
          }
      

      更多详情可以查看hereherehere

      【讨论】:

        【解决方案3】:

        您可以在 html 中放置一个仅在验证出现错误时才存在的 div。然后在循环中显示每个错误:

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

        这样,当您返回此视图时,您的字段将出现错误,因此将显示此代码。

        【讨论】:

        • 是的,我有。由于某种原因,它被切断了,已经编辑过了
        猜你喜欢
        • 2017-07-14
        • 1970-01-01
        • 2020-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-23
        • 1970-01-01
        • 2020-06-09
        相关资源
        最近更新 更多