I have a bean that has many fields annotated with JSR-303 validation annotations. Now a new requirement arises that one of the fields is required, but only under certain conditions.
I looked around and found what I needed, verification teams.
This is what I have now:
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 check in 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); }
It turns out that all annotated non-group checks are ignored, and I get only 1 violation.
I can understand this behavior, but I would like to know if there is a way to get the group to include all non-annotated parameters. If not, I will 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;
The real class I'm working with has a lot more fields (about 20), so this method turns what was an explicit way to show validations into a big mess.
Can someone tell me if there is a better way? Maybe something like:
vf.getValidator().validate(dto, EmployeeDTO.ValidatedOnCreationOnly.class, NonGroupSpecific.class);
I use this in a spring project, so if spring has a different way, I will be happy to know.