代码之家  ›  专栏  ›  技术社区  ›  Mahmoud Saleh

同一属性上的不同Hibernate验证批注

  •  2
  • Mahmoud Saleh  · 技术社区  · 14 年前

    我正在对bean中的一个属性使用两个验证注释:

    @NotEmpty(message = "{name.required}")
    @Pattern(regex = "^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$", message = "{invalid.name}")
    private String name;
    

    (如果出现第一个条件,则显示其错误消息,然后跳过第二个条件)。

    2 回复  |  直到 8 年前
        1
  •  4
  •   dira    14 年前

    如果出现第一个条件,则显示其错误消息,然后跳过第二个条件

    这可以通过创建复合约束并使用@ReportAsSingleViolation元约束对其进行注释来完成。

    @ReportAsSingleViolation
    @NotEmpty
    @Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
    @Constraint(validatedBy = {})
    public @interface UserName {
        String message() default "invalid userName!";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    参考 3.2. Constraint composition

        2
  •  3
  •   reversebind    7 年前

    接受的答案并不像你所期望的那样有效。只有当您想列出 全部 中的错误 全部

    文件 @ReportAsSingleViolation 忽略每个单独组合约束的错误报告

    使用接受示例

    @ReportAsSingleViolation
    @NotEmpty
    @Pattern(regexp="^([A-Za-z0-9]{2,}(\\-[a-zA-Z0-9])?)$")
    @Constraint(validatedBy = {})
    public @interface UserName {
        String message() default "invalid userName!";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    这意味着您将得到 UserName 注释为“无效用户名!”即使@NotEmpty首先失败。。。。

    我必须说,我对java bean验证实现程序的糟糕设计感到非常震惊。如果返回完全不相关的消息,那么使用组合验证是完全没有意义的。它应该首先失败,并返回实际失败的验证对应的错误!。无论如何,没有大规模的丑陋的黑客攻击是无法做到这一点的。如此简单的验证任务变成了一场噩梦。0欧

    @Target({ElementType.METHOD, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = PasswordValidator.class)
    public @interface Password {
        String message() default "{com.example.Password.message}";
    
        Class<?>[] groups() default { };
    
        Class<? extends Payload>[] payload() default { };
    }
    
    
    
    public class PasswordValidator implements ConstraintValidator<Password, String> {
        private Pattern twoDigitsPattern;
    
        public void initialize(Password constraint) {
            twoDigitsPattern = Pattern.compile("(.*[\\d]){2}");
        }
    
        public boolean isValid(String password, ConstraintValidatorContext context) {
            context.disableDefaultConstraintViolation();
    
            if (password == null) {
                context.buildConstraintViolationWithTemplate("{javax.validation.constraints.NotNull.message}")
                        .addConstraintViolation();
                return false;
            }
    
            if (password.length() < 5 || password.length() > 10) {
                context.buildConstraintViolationWithTemplate("must be between 5 to 10 characters")
                        .addConstraintViolation();
                return false;
            }
    
            if (!twoDigitsPattern.matcher(password).matches()) {
                context.buildConstraintViolationWithTemplate("must contain 2 digits between [0-9]").addConstraintViolation();
                return false;
            }
    
            return true;
        }
    

    }