gpt4 book ai didi

java - Spring + Thymeleaf 自定义验证展示

转载 作者:行者123 更新时间:2023-11-29 04:59:18 25 4
gpt4 key购买 nike

我一直在尝试让自定义 javax 验证正常工作(Spring Boot 和 Thymeleaf),但我不知道如何显示错误消息。问题似乎是,“正常”错误(例如@Size、@NotNull 等)似乎在绑定(bind)结果中添加了 FieldError。我的自定义 validator 虽然提供了一个 ObjectError。我不知道如何让 Thymeleaf 显示我的自定义错误(显然已通过,因为 th:errors="*{*}" 显示了它)。

非常感谢任何帮助。

更新:我现在可以通过

显示错误消息
<p th:if="${#fields.hasErrors('${user}')}" th:errors="${user}"></p>

但是,如果我需要一个以上的 validator (例如确认密码和确认电子邮件),此解决方案将不起作用(或者如果一个不合适则显示两条错误消息。如果您有任何建议,请不要犹豫。

p>

下面是我为此使用的代码:

模板:

<p th:if="${#fields.hasErrors('username')}"th:errors="*{username}"></p>
<!-- works just fine -->
<p th:if="${#fields.hasErrors('*')}" th:errors="*{*}"></p>
<!-- works and displays all errors (for every field with an error,
including my custom validator) -->
<p th:if="${#fields.hasErrors('confirmPassword')}" th:errors="*{*}"></p>
<!-- does not work -->
<p th:if="${#fields.hasErrors('*')}" th:errors="*{confirmPassword}"></p>
<!-- does not work -->

validator 实现:

public class PasswordsEqualConstraintValidator implements
ConstraintValidator<PasswordsEqualConstraint, Object> {

@Override
public void initialize(PasswordsEqualConstraint arg0) {
}

@Override
public boolean isValid(Object candidate, ConstraintValidatorContext arg1) {
User user = (User) candidate;
return user.getPassword().equals(user.getConfirmPassword());
}
}

validator 接口(interface):

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = PasswordsEqualConstraintValidator.class)
public @interface PasswordsEqualConstraint {
String message();

Class<?>[] groups() default {};

Class<? extends Payload>[] payload() default {};
}

用户.java:

@PasswordsEqualConstraint(message = "passwords are not equal")
public class User implements java.io.Serializable {
...
@Size(min=2, max=40)
private String username;
...
private String confirmPassword;
...

Controller :

@RequestMapping(value = "/signup", method = RequestMethod.POST)
public String signup(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "signup";
}
... do db stuff .. return "success";
}

最佳答案

这可能是因为您的@PasswordsEqualConstraint 分配给了整个 bean(类型)而不是字段“confirmPassword”。要向具体字段添加可能的约束违规,您可以像下面的示例一样。

FieldMatch 比较两个字段,如果它们不相等,则将验证错误分配给第二个字段。

顺便说一句。这是您正在做的事情的更通用的解决方案。例如,对于密码,您可以像

@FieldMatch(first = "password", second = "confirmPassword", message = "Passowords are not equal.")

validator :

public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> {

private String firstFieldName;
private String secondFieldName;

@Override
public void initialize(final FieldMatch constraintAnnotation) {
firstFieldName = constraintAnnotation.first();
secondFieldName = constraintAnnotation.second();
}

@Override
public boolean isValid(final Object value, final ConstraintValidatorContext context) {
try {
final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
final Object secondObj = BeanUtils.getProperty(value, secondFieldName);

boolean isValid = firstObj == null && secondObj == null || firstObj != null && firstObj.equals(secondObj);

if (!isValid) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()).addNode(secondFieldName).addConstraintViolation();
}

return isValid;
}
catch (final Exception ignore) {
// ignore
}
return true;
}
}

关于java - Spring + Thymeleaf 自定义验证展示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32611556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com