Reputation: 8196
I am trying to use JSR-303 Bean Validation with Hibernate Validator to ensure that a collection does not contain null values.
I know that I can annotate my collection as follows:
@Valid
@NotEmpty
private Set<EmailAddress> emails = new HashSet<>();
This does the job for ensuring that the collection itself is not null or empty and in the case that I add a non-null EmailAddress element it also validates this correctly. However, it doesn't prevent adding a null element.
Is there a way to prevent a null element being added to the collection? In an ideal world the solution would be declarative (like the rest of the validation) and wouldn't involve programmatically iterating through the collection manually doing null checks.
Thanks in advance!
Upvotes: 0
Views: 975
Reputation: 173
Bean Validation is missing the @NotBlank annotation for Collections that would pretty much fit the scenario you are describing. Basically, as you mentioned, you would require to implement a custom validator that will programatically check that the contents of the collection ensuring that none of the elements inside it are null.
Here is an example of the custom validator you would need:
public class CollectionNotBlankValidator implements
ConstraintValidator<CollectionNotBlank, Collection> {
@Override
public void initialize(CollectionNotBlank constraintAnnotation) {
}
@Override
public boolean isValid(Collection value, ConstraintValidatorContext context) {
Iterator<Object> iter = value.iterator();
while(iter.hasNext()){
Object element = iter.next();
if (element == null)
return false;
}
return true;
}
}
As you can see I have named the custom annotaion CollectionNotBlank. Here is an example of the code for the custom annotation:
@Target(FIELD)
@Retention(RUNTIME)
@Constraint(validatedBy = CollectionNotBlankValidator.class)
@ReportAsSingleViolation
@Documented
public @interface CollectionNotBlank {
String message() default "The elements inside the collection cannot be null values.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Upvotes: 2