@Valid annotation is not validating the list of child objects
Adding to @Ritesh answer, @Valid
constraint will instruct the Bean Validator to delve to the type of its applied property and validate all constraints found there. Answer with code to your question, the validator, when seeing a @Valid
constraint on addresses
property, will explore the AddressForm
class and validate all JSR 303
constraints found inside, as follows:
public class UserAddressesForm {
@NotEmpty
private String firstName;
@NotEmpty
private String lastName;
@Valid
private List<AddressForm> addresses;
...
setters and getters
public class AddressForm {
@NotEmpty
private String customName;
@NotEmpty
private String city;
@NotEmpty
private String streetAn;
@NotEmpty
private String streetHn;
@NotEmpty
private String addressCountry;
@NotEmpty
private String postCode;
...
setters and getters
You need to decorate addresses
member of UserAddressesForm
with @Valid
annotation. See section 3.1.3 and 3.5.1 of JSR 303: Bean Validation. As I explained in my answer to the question Is there a standard way to enable JSR 303 Bean Validation using annotated method, this is the real use of @Valid
annotation as per JSR 303.
Edit Example code: Hibernate Validator- Object Graph. (The list of passengers in Car)
Edit From Hibernate Validator 6 Reference doc:
In versions prior to 6, Hibernate Validator supported cascaded validation for a subset of container elements and it was implemented at the container level (e.g. you would use
@Valid private List<Person>
to enable cascaded validation forPerson
).This is still supported but is not recommended. Please use container element level
@Valid
annotations instead as it is more expressive.
Example:
public class Car {
private List<@NotNull @Valid Person> passengers = new ArrayList<Person>();
private Map<@Valid Part, List<@Valid Manufacturer>> partManufacturers = new HashMap<>();
//...
}
Also see what's new in Bean Validation 2.0/Jakarta Bean Validation.