类似的问题在此处发布-> Spring + Thymeleaf custom validation display,但我不知道解决方案,因此发布此新问题。 我有一个简单的注册表格,其中包含用户名,电子邮件,密码和ConfirmPassword字段
<form action="#" th:action="@{/register}" th:object="${user}"
method=post>
<!--error detection start -->
<div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
<p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>
</div>
<!--error detection ends -->
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-user"></i>
</span>
</div>
<input name="username" th:field="*{username}" class="form-control"
placeholder="User Name" type="text">
</div>
<div class="form-group input-group"
th:if="${#fields.hasErrors('username')}" th:errors="*{username}">Name
Error</div>
<!-- form-group// -->
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-envelope"></i>
</span>
</div>
<input name="email" th:field="*{email}" class="form-control"
placeholder="Email address" type="email">
</div>
<div class="form-group input-group"
th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Name
Error</div>
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-lock"></i>
</span>
</div>
<input class="form-control" th:field="*{password}"
placeholder="Create password" type="password">
</div>
<!-- form-group// -->
<div class="form-group input-group">
<div class="input-group-prepend">
<span class="input-group-text"> <i class="fa fa-lock"></i>
</span>
</div>
<input class="form-control" th:field="*{confirmPassword}"
placeholder="Repeat password" type="password">
<p class="error-message"
th:each="error: ${#fields.errors('user.confirmPassword')}"
th:text="${error}">Validation error</p>
</div>
<!-- form-group// -->
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">
Create Account</button>
</div>
<!-- form-group// -->
<p class="text-center">
Have an account? <a href="">Log In</a>
</p>
</form>
我添加了一个自定义验证,该验证将在密码和确认密码字段不匹配时触发。
1.FieldsValueMatchValidator
public class FieldsValueMatchValidator implements ConstraintValidator<FieldsValueMatch, Object> {
private String field;
private String fieldMatch;
public void initialize(FieldsValueMatch constraintAnnotation) {
this.field = constraintAnnotation.field();
this.fieldMatch = constraintAnnotation.fieldMatch();
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field);
Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch);
if (fieldValue != null) {
return fieldValue.equals(fieldMatchValue);
} else {
return fieldMatchValue == null;
}
}
}
3.FieldsValueMatch
@Constraint(validatedBy = FieldsValueMatchValidator.class)
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface FieldsValueMatch {
String message() default "Fields values don't match!";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String field();
String fieldMatch();
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface List {
FieldsValueMatch[] value();
}
}
4.User.java
@FieldsValueMatch(field = "password", fieldMatch = "confirmPassword", message = "Passwords do not match!")
@Entity
public class User implements UserDetails
{
@NotBlank
private String password;
@Transient
@NotBlank
private String confirmPassword;
//other getters and setters
}
5。控制器代码
@PostMapping("/register")
public String saveNonJsonData(@Valid @ModelAttribute("user") User theUser, BindingResult errors) {
if (errors.hasErrors()) {
return "register";
}
else
{
//successlogic
}
自定义验证程序运行正常,我可以在百里香页面上使用以下代码在页面上看到错误消息
<!--error detection start -->
<div class="alert alert-danger" th:if="${#fields.hasErrors('*')}">
<p th:each="err : ${#fields.errors('*')}" th:text="${err}"></p>
</div>
<!--error detection ends -->
如此处所述-Spring + Thymeleaf custom validation display,问题是自定义验证程序返回用于密码字段匹配验证的ObjectError而不是fieldError。即使我尝试提供解决方案,但仍无法弄清楚如何让Thymeleaf显示我的自定义错误。
更新 在这里Displaying "Passwords don't match" custom annotation message还有一个答案,现在我可以使用以下代码查看错误消息
<input class="form-control" th:field="*{confirmPassword}" placeholder="Repeat password" type="password">
<div class="form-group input-group" th:if="${#fields.hasErrors('global')}" th:errors="*{global}"></div>
我更新的问题是,如果我还有两个字段,例如“电子邮件”和“ confirmEmail”字段,那么这种方法如何在百里香页面上起作用?