这可能是因为您的@PasswordsEqualConstraint被分配给整个bean(类型)而不是字段“
/confirm/iPassword”。要将可能违反约束的条件添加到具体字段,您可以像以下示例一样进行 *** 作。
如果两个字段不相等,则FieldMatch比较两个字段,然后将验证错误分配给第二个字段。
顺便说一句。这是您正在做的事情的更通用的解决方案。密码示例,您可以像这样使用它
@FieldMatch(first = "password", second = "/confirm/iPassword", message = "Passowords are not equal.")
验证器:
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; }}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)