Validator interface:
@Target({ ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = { CustomValidatorValidator.class })
@Documented
public @interface CustomValidator{
String message() default "Put here your default message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
ValidatorImplementation:
public final class CustomValidatorValidator implements ConstraintValidator<CustomValidator, List<WorkgroupId>> {
@Override
public void initialize(CustomValidator constraintAnnotation) {
}
@Override
public boolean isValid(List<WorkgroupId> yourlist, ConstraintValidatorContext context) {
if (yourlist== null)
return true;
else
return yourlist.stream().anyMatch(s -> /* filter here as you want */);
}
}
Notice we return true
if the field is null, I do it like this because I just put @NotNull
constraint if I need not to be null so I have more control over the constraint.
Finally:
@JsonProperty("workgroups")
@CustomValidator
private List<WorkgroupId> workgroupIds = new ArrayList<>();
P.S: I don't understand why you initialize the list in this last code. If that's a field you're supposed to receive through the request then you don't need to initialize it, the json deserializer will initialize it with the incoming field in the json.