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?
Bean Validation. JSR-303 bean validation is an specification whose objective is to standardize the validation of Java beans through annotations. The objective of the JSR-303 standard is to use annotations directly in a Java bean class.
Apache Bean Validation (formerly agimatec)
JavaBeans Validation (Bean Validation) is a new validation model available as part of Java EE 6 platform. The Bean Validation model is supported by constraints in the form of annotations placed on a field, method, or class of a JavaBeans component, such as a managed bean. Constraints can be built in or user defined.
@NotNull The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With