Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Java Bean Validators (JSR-303/JSR-349) on elements of an array/list/collection

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?

like image 720
Eric B. Avatar asked Dec 04 '13 19:12

Eric B.


People also ask

What is JSR 303 Bean Validation?

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.

In which implementation is the JSR 303 standard used?

Apache Bean Validation (formerly agimatec)

How can you explain Bean Validation?

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.

What does @NotNull annotation mean in bean property?

@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.


2 Answers

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;
like image 120
Gunnar Avatar answered Nov 07 '22 12:11

Gunnar


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.

like image 21
Jakub Jirutka Avatar answered Nov 07 '22 13:11

Jakub Jirutka