6

我正在使用 JSR303 并创建了一个类级别的约束,该约束在一个表单中比较密码及其确认,我将在此将其命名为 @SameAs 约束。理想情况下,我希望将约束与预期目标(confirmPassword)相关联,但显然封闭的 bean 不可用于提取密码道具。- 因此是类级别的约束。

我感兴趣地阅读了其他帖子,演示如何利用类级约束来验证关系,但找不到任何解释如何自定义约束违反以与子路径相关联的内容,在这种情况下是两个字段之一在关系中。

我的问题如下:我如何将来自约束违规的消息与“confirmPassword”字段而不是顶级对象相关联?我尝试使用 javax.Validator.validate(target, context) 的上下文参数,但是在 @SameAs 的验证器中添加一个节点会导致级联中的下一个约束出现异常(尝试提取 confirmPassword -> orderNumber 属性而不是 order -> orderNumber ) 结果。

目前,我通过创建一个额外的属性来存储约束消息,该属性被提取出来以在 Web 层上的 confirmPassword 输入字段附近使用,从而使用了一个丑陋的组合。

当然我在这里遗漏了一些东西......请参见下面的示例

感谢您的任何评论

例子

@Constraint( validatedBy = { SamePwdAsValidator.class})
public interface SamePwdAs {//...
}

//Using passwords in an order doesn't make sense - only for demo purpose
@SamePwdAs( message = "Password and confirmation must match" ...)
public class Order {

    @NotNull
    @Size(....)
    String pwd;

    //where I would really like to use @SameAs, and associate a violation 
    String pwdConfirm;

    @NotNull (...)
    @Pattern (....)
    String orderNumber;

    //...getters/setters
}

public class SamePwdAsValidator implements javax.validation.Validator {
//...
  public boolean isValid( Object target, ValidationContext ctx) {
   String tgt = target.getPwd(), other = target.getPwdConfirm()
   boolean isValid = tgt.equals( other);

   if ( !isValid) {
      //try to configure the context subpath for pwdConfirm to associate this constraint violation with: I tried 
      //ctx.addNode( 'pwdConfirm').addConstraintViolation() which doesn't work, as the next validator will
      //bump into trying to extract Order.pwdConfirm.orderNumber and throw a NoPropertyFoundException or the like
   }

   return isValid;
}
4

1 回答 1

6

我要给出2个答案。

回答 1,努力回答您的问题:

我使用这样的实用方法:

public static final void recreateConstraintViolation(ConstraintValidatorContext constraintValidatorContext, String errorCode, String fieldName) {
        constraintValidatorContext.disableDefaultConstraintViolation();
        constraintValidatorContext.buildConstraintViolationWithTemplate(errorCode).
        addNode(fieldName).addConstraintViolation();

}

然后,在您比较两个密码的验证器中:

if ( !isValid) {
    for (String fieldName : fieldNames) {
        CustomConstraintUtils.recreateConstraintViolation(constraintValidatorContext, "password.password2.mismatch", fieldName);
    }
    return false;
}

答案 2

我建议您使用像 Spring Security 这样的安全框架来处理密码匹配,因为我认为您的用例正在处理用户登录。

于 2011-06-14T15:55:43.650 回答