Bean 验证规范优先级

Bean validation specification prioritizing

我正在使用 bean 验证规范来验证我在 spring-boot thymeleaf 项目上的表单。 我的实体 属性 如下。

@NotEmpty(message = "{Password should not be empty}")
@Pattern(regexp = //Pattern for range 1-20, message = "{Wrong Input}")
private String            password;

当我 运行 并在我的表单的密码字段中输入空值时,显示了两条验证错误消息。

我的期望是,当输入空值时,只有@NotEmpty 注释应该起作用,另一方面,只有@Pattern 应该在用户输入错误时显示。

我该如何处理 Bean 验证规范?

此致。

1。 Validation groups

@NotEmpty(groups = First.class), message = ...,          
@Pattern(groups = Second.class, regexp = ...)
private String password;

创建验证组:

//Validation Groups - Just empty interface used as Group identifier
public interface First {
}
public interface Second {
}

并以这种方式验证模型:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
Set<ConstraintViolation<Model>> violations = validator.validate(model, First.class);

if(violations.isEmpty()){
     violations = validator.validate(model, Second.class);
}

2。 Groups Sequences

我从来没有用过它们,但它似乎正是你想要的

检查其他答案 ()。我在下面添加了这个答案的引用(来自 @Gunnar),具有讽刺意味的是,它还使用了 FirstSecond组名:

@GroupSequence({First.class, Second.class})
public interface Sequence {}

@Size(min = 2, max = 10, message = "Name length improper", groups = { First.class })
@Pattern(regexp = "T.*", message = "Name doesn't start with T" , groups = { Second.class })
private String name;

When now validating a Bean instance using the defined sequence (validator.validate(bean, Sequence.class)), at first the @Size constraint will be validated and only if that succeeds the @Pattern constraint.

使用此解决方案,您无需手动调用 validator.validate(...),如果验证失败,将按照序列中定义的顺序执行验证 short-circuit。