JavaBean Validation - Collection Validation

[Updated: Aug 7, 2017, Created: Aug 7, 2017]

Just like object references can be validated recursively by using @Valid (as we saw in the last example), the elements of Java Collections, arrays and Iterable can also be validated by using @Valid annotation.

Example

public class ValidAnnotationExample {

    private static class Department {
        @NotNull
        @Valid
        private List<Employee> employees;
        @NotNull
        private String name;

        public Department(String name, List<Employee> employees) {
            this.employees = employees;
            this.name = name;
        }
    }

    private static class Employee {
        @NotNull
        private String name;
        @Pattern(regexp = "\\d{3}-\\d{3}-\\d{4}")
        private String phone;

        public Employee(String name, String phone) {
            this.name = name;
            this.phone = phone;
        }
    }

    public static void main(String[] args) throws ParseException {
        Employee e1 = new Employee(null, "333333");
        Employee e2 = new Employee("Jake", "abc");

        Department dept = new Department("Admin", Arrays.asList(e1, e2));

        Validator validator = createValidator();
        Set<ConstraintViolation<Department>> violations = validator.validate(dept);
        if (violations.size() == 0) {
            System.out.println("No violations.");
        } else {
            System.out.printf("%s violations:%n", violations.size());
            violations.stream()
                      .forEach(ValidAnnotationExample::printError);
        }
    }

    private static void printError(ConstraintViolation<?> violation) {
        System.out.println(violation.getPropertyPath()
                + " " + violation.getMessage());
    }

    public static Validator createValidator() {
        Configuration<?> config = Validation.byDefaultProvider().configure();
        ValidatorFactory factory = config.buildValidatorFactory();
        Validator validator = factory.getValidator();
        factory.close();
        return validator;
    }
}

Output

3 violations:
employees[1].phone must match "\d{3}-\d{3}-\d{4}"
employees[0].name may not be null
employees[0].phone must match "\d{3}-\d{3}-\d{4}"

As seen, the List elements (employees) were validated as expected.

Let's remove @Valid annotation in above example:

Output

No violations.

Example Project

Dependencies and Technologies Used :

  • hibernate-validator 5.2.4.Final: Hibernate's Bean Validation (JSR-303) reference implementation..
  • javax.el-api 2.2.4 Expression Language API 2.2
  • javax.el 2.2.4 Expression Language 2.2 Implementation
  • JDK 1.8
  • Maven 3.3.9

Collection Validation by Using @Valid Select All Download
  • valid-annotation-with-collection-example
    • src
      • main
        • java
          • com
            • logicbig
              • example

See Also