Search code examples
javahibernate-validator

@Valid annotation is ignored with validating groups


I have two beans:

public class User {
    @NotNull
    public String name;

    @NotNull(groups = {Default.class, ChangeCheckGroup.class})
    public String password;

    @Valid
    public Details details;
}

and

public class Details {
    @NotNull(groups = {Default.class, ChangeCheckGroup.class})
    public String email;
}

I am using Hibernate Bean Validator to manually validate User bean.

When i am trying to validate bean using no validating groups at all, it works as expected.

Set<ConstraintViolation> cv = validator.validate( entitie );

It will check user.name, user.password, user.details.email.

But when i am trying to use validator with custom ChangeCheckGroup validating group, it ignores @Valid annotation.

Set<ConstraintViolation> cv = validator.validate( entitie, groups );

Will check only user.password, and there will no check of an user.details.email.

Is there any way to validate bean and beans it holds using validating groups?


Solution

  • The only way in which your scenario could skip the inner validations for the Detail class would be that the User object has the details field set to null. The Validator would still consider the details null value as valid (since you did not specify a @NotNull annotation specifically for that field in any of the groups).

    So, the Bean Validation annotations inside the Detail class will be ignored. Once you properly initialize the attribute details inside User, it will be validated according to the indicated group.