How to use Java Bean Validators (JSR-303/JSR-349) on elements of an array/list/collection
bean-validation, java, validation
Solution
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;
Problem
I'm new to using Java Bean validation (JSR-303/JSR-349/Hibernate Validator), and understand the general concepts. However, I'm not sure how to validate the contents of an composed type vs the type itself. For example: ``` @NotNull private List<String> myString; ``` will validate that the List myString is not null, but does nothing for validating the contents of the list itself. Or given other types of validators (Min/Max/etc), how do I validate the individual elements of the List? Is there a generic solution for any composed type?