Close

Java Bean Validation - Collection Validation

[Last Updated: Sep 12, 2021]

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

package com.logicbig.example;

import javax.validation.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Set;

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().sorted(Comparator.comparing(o -> o.getPropertyPath().toString()))
                      .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[0].name must not be null
employees[0].phone must match "\d{3}-\d{3}-\d{4}"
employees[1].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:

package com.logicbig.example;

import javax.validation.*;
import javax.validation.constraints.Digits;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import java.text.ParseException;
import java.util.Date;
import java.util.Set;

public class WithoutValidAnnotationExample {

    private static class DriverLicense {
        @NotNull
        private Driver driver;
        @Digits(integer = 7, fraction = 0)
        private int number;

        public DriverLicense(Driver driver, int number) {
            this.driver = driver;
            this.number = number;
        }
    }

    private static class Driver {
        @NotNull
        private String fullName;
        @Min(100)
        private int height;
        @Past
        @NotNull
        private Date dateOfBirth;

        public Driver(String fullName, int height, Date dateOfBirth) {
            this.dateOfBirth = dateOfBirth;
            this.fullName = fullName;
            this.height = height;
        }
    }

    public static void main(String[] args) throws ParseException {
        Driver driver = new Driver("Joseph Waters", 60,
                new Date(System.currentTimeMillis() + 100000));
        DriverLicense dl = new DriverLicense(driver, 3454343);

        Validator validator = createValidator();
        Set<ConstraintViolation<DriverLicense>> violations = validator.validate(dl);
        if (violations.size() == 0) {
            System.out.println("No violations.");
        } else {
            System.out.printf("%s violations:%n", violations.size());
            violations.stream()
                      .forEach(WithoutValidAnnotationExample::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

No violations.

Example Project

Dependencies and Technologies Used:

  • hibernate-validator 6.2.0.Final (Hibernate's Jakarta Bean Validation reference implementation)
     Version Compatibility: 5.0.0.Final - 6.2.0.Final Version List
    ×

    Version compatibilities of hibernate-validator with this example:

      groupId: org.hibernate
      artifactId: hibernate-validator
      Reference implementation for Bean Validation 1.1
    • 5.0.0.Final
    • 5.0.1.Final
    • 5.0.2.Final
    • 5.0.3.Final
    • 5.1.0.Final
    • 5.1.1.Final
    • 5.1.2.Final
    • 5.1.3.Final
    • 5.2.0.Final
    • 5.2.1.Final
    • 5.2.2.Final
    • 5.2.3.Final
    • 5.2.4.Final
    • 5.2.5.Final
    • 5.3.0.Final
    • 5.3.1.Final
    • 5.3.2.Final
    • 5.3.3.Final
    • 5.3.4.Final
    • 5.3.5.Final
    • 5.3.6.Final
    • 5.4.0.Final
    • 5.4.1.Final
    • 5.4.2.Final
    • 5.4.3.Final
    • groupId: org.hibernate.validator
      artifactId: hibernate-validator
      Reference implementation for Bean Validation 2.0
    • 6.0.0.Final
    • 6.0.1.Final
    • 6.0.2.Final
    • 6.0.3.Final
    • 6.0.4.Final
    • 6.0.5.Final
    • 6.0.6.Final
    • 6.0.7.Final
    • 6.0.8.Final
    • 6.0.9.Final
    • 6.0.10.Final
    • 6.0.11.Final
    • 6.0.12.Final
    • 6.0.13.Final
    • 6.0.14.Final
    • 6.0.15.Final
    • 6.0.16.Final
    • 6.0.17.Final
    • 6.0.18.Final
    • 6.0.19.Final
    • 6.0.20.Final
    • 6.0.21.Final
    • 6.0.22.Final
    • 6.1.0.Final
    • 6.1.1.Final
    • 6.1.2.Final
    • 6.1.3.Final
    • 6.1.4.Final
    • 6.1.5.Final
    • 6.1.6.Final
    • 6.1.7.Final
    • 6.2.0.Final
    • Version 7 and later:
      Jakarta Bean Validation 3.0
      jakarta.* packages

    Versions in green have been tested.

  • javax.el-api 3.0.0 (Expression Language 3.0 API)
  • javax.el 2.2.6 (Expression Language 2.2 Implementation)
  • JDK 8
  • Maven 3.8.1

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

    See Also