草庐IT

java - JSR303 : Trying to customize a constraint violation to be associated with a sub-path in a class-level relationship constraint validator

coder 2024-03-31 原文

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

我感兴趣地阅读了其他展示如何利用类级约束来验证关系的帖子,但找不到任何解释如何自定义约束违规以与子路径相关联的内容,在本例中为关系中的两个字段。

我的问题如下:如何将违反约束的消息与“confirmPassword”字段而不是顶级对象相关联?我尝试使用 javax.Validator.validate(target, context) 的上下文参数,但是在 @SameAs 的 validator 中添加一个节点会导致级联中的下一个约束出现异常(尝试提取 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;
}

最佳答案

我将给出 2 个答案。

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

我使用这样的实用方法:

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

}

然后,在您比较两个密码的 validator 中:

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

答案 2

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

关于java - JSR303 : Trying to customize a constraint violation to be associated with a sub-path in a class-level relationship constraint validator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4932958/

有关java - JSR303 : Trying to customize a constraint violation to be associated with a sub-path in a class-level relationship constraint validator的更多相关文章

随机推荐