Spring类级别验证和Thymeleaf

时间:2018-06-10 16:32:37

标签: spring validation thymeleaf

我正在学习Spring Framework和Thymeleaf。我已经知道如何使用${#fields.errors("xx")}之类的东西来显示字段错误。但是,我对如何在Thymeleaf中显示对象错误消息感到困惑。

这是我的 UserForm 类:

@PasswordMatches
public class UserForm {
    @NotNull
    @NotEmpty
    private String username;
    @NotNull
    @NotEmpty
    private String password;
    @NotNull
    @NotEmpty
    private String matchingPassword;
    @NotNull
    @NotEmpty
    @ValidEmail
    private String email;

    /* setter and getter methods */

这是我的 PasswordMatches 注释:

@Target({ElementType.TYPE, ElementType.FIELD, ElementType.ANNOTATION_TYPE}) 
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PasswordMatchesValidator.class)
@Documented
public @interface PasswordMatches { 
    String message() default "Passwords don't match";
    Class<?>[] groups() default {}; 
    Class<? extends Payload>[] payload() default {};
}

class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {  
    @Override
    public void initialize(PasswordMatches constraintAnnotation) {       
    }

    @Override
    public boolean isValid(Object obj, ConstraintValidatorContext context){   
        UserDto user = (UserDto) obj;
        return user.getPassword().equals(user.getMatchingPassword());    
  }     
}

以下是我的控制器方法:

@RequestMapping(value="/registration", method=RequestMethod.POST)
public ModelAndView registerUserAccount(@ModelAttribute("user") @Valid UserForm userForm,
          BindingResult result, WebRequest request, Errors errors) {
    if (!result.hasErrors()) {
        return new ModelAndView("registerSuccess");
    }
    else {
        return new ModelAndView("registration", "user", userForm);
    }
}

现在我的问题是:如果 密码 字段与 confirmPass 字段不匹配,我可以获取Thymeleaf中类级别注释返回的默认错误消息吗?

3 个答案:

答案 0 :(得分:3)

我知道这是旧帖子,但是我也遇到了这个问题,这是解决方法(也许它也可以帮助其他人): 将PasswordMatchesValidator修改为此:

class PasswordMatchesValidator implements ConstraintValidator<PasswordMatches, Object> {  
@Override
public void initialize(PasswordMatches constraintAnnotation) {       
}

@Override
public boolean isValid(Object obj, ConstraintValidatorContext context){   
    UserDto user = (UserDto) obj;
    boolean isValid = user.getPassword().equals(user.getMatchingPassword());
    if(!isValid){
         context.disableDefaultConstraintViolation();
        context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate())
                .addPropertyNode( "matchingPassword" ).addConstraintViolation();
    }
    return isValid;

}

它将验证结果绑定到您的“ matchingPassword”属性。因此,在您的百里香模板中,如下所示:

${#fields.errors("matchingPassword")}

答案 1 :(得分:1)

form标记内添加:

<p data-th-each="err : ${#fields.allErrors()}" data-th-text="${err}" class="error">
  Invalid input.
</p>

答案 2 :(得分:0)

  <p th:if="${#fields.hasErrors('${yourObject}')}" th:errors="${yourObject}"></p>