How to use Java Bean Validators (JSR-303/JSR-349) on elements of an array/list/collection
There is no easy generic solution as of Bean Validation 1.0/1.1. You could implement a custom constraint like @NoNullElements
:
@NoNullElements
private List<String> myStrings;
The constraint's validator would iterate over the list and check that no element is null. Another approach is to wrap your String into a more domain-specific type:
public class EmailAddress {
@NotNull
@Email
private String value;
//...
}
And apply cascaded validation to the list via @Valid
:
@Valid
private List<EmailAddress> addresses;
Having such a domain-specific data type is often helpful anyways to convey a data element's meaning as it is passed through an application.
In the future a generic solution for the issue may be to use annotations on type parameters as supported by Java 8 but that's only an idea at this point:
private List<@NotNull String> myStrings;
Take a look at validator-collection – it’s very easy to use any Constraint Annotation on a collection of simple types with this library. Also see https://stackoverflow.com/a/16023061/2217862.