JSR-303验证组定义默认组 [英] JSR-303 validation groups define a default group
问题描述
我有一个bean,它有很多用JSR-303验证注释注释的字段.现在有一个新的要求,其中一个字段是强制性的,但仅在某些条件下才可以.
I have a bean that has a lot of fields annotated with JSR-303 validation annotations. There is a new requirement now that one of the fields is mandatory, but only in certain conditions.
我环顾四周,找到了我需要的验证组.
I looked around and have found what I needed, validation groups.
这就是我现在拥有的:
public interface ValidatedOnCreationOnly {
}
@NotNull(groups = ValidatedOnCreationOnly.class)
private String employerId;
@Length(max = 255)
@NotNull
private String firstName;
@Length(max = 255)
@NotNull
private String lastName;
但是,当我在单元测试中运行此验证时:
However, when I run this validation in a unit test:
@Test
public void testEmployerIdCanOnlyBeSetWhenCreating() {
EmployeeDTO dto = new EmployeeDTO();
ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Set<ConstraintViolation<EmployeeDTO>> violations = vf.getValidator().validate(dto, EmployeeDTO.ValidatedOnCreationOnly.class);
assertEquals(violations.size(), 3);
}
事实证明,所有非组批注的验证都将被忽略,而我仅收到1次违规.
It turns out that all of the non-group annotated validations are ignored and I get only 1 violation.
我可以理解这种行为,但是我想知道是否有一种方法可以使该组也包括所有未注释的参数.如果没有的话,我将不得不做这样的事情:
I can understand this behaviour but I would like to know if there is a way I can make the group include all non-annotated parameters as well. If not I'd have to do something like this:
public interface AlwaysValidated {
}
public interface ValidatedOnCreationOnly extends AlwaysValidated {
}
@NotNull(groups = ValidatedOnCreationOnly.class)
private String employerId;
@Length(max = 255, groups = AlwaysValidated.class)
@NotNull(groups = AlwaysValidated.class)
private String firstName;
@Length(max = 255, groups = AlwaysValidated.class)
@NotNull(groups = AlwaysValidated.class)
private String lastName;
我正在使用的真实类具有更多字段(大约20个),因此该方法将一种清晰的方式将验证显示为混乱.
The real class I'm working with has a lot more fields (about 20), so this method turns what was a clear way of indicating the validations into a big mess.
谁能告诉我是否有更好的方法?也许像这样:
Can anyone tell me if there is a better way? Maybe something like:
vf.getValidator().validate(dto, EmployeeDTO.ValidatedOnCreationOnly.class, NonGroupSpecific.class);
我正在spring项目中使用它,所以如果spring还有另一种方式,我将很高兴知道.
I'm using this in a spring project so if spring has another way I'll be glad to know.
推荐答案
javax.validation.groups.Default
中有一个Default
组,它代表默认的Bean验证组.除非明确定义了组列表:
There is a Default
group in javax.validation.groups.Default
, which represents the default Bean Validation group. Unless a list of groups is explicitly defined:
- 约束属于
Default
组 - 验证适用于
Default
组
- constraints belong to the
Default
group - validation applies to the
Default
group
您可以扩展此组:
public interface ValidatedOnCreationOnly extends Default {}
这篇关于JSR-303验证组定义默认组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!