Search code examples
javaspring-mvchibernate-validator

Two hibernate validators on one field. Need to choose only one


I have a class:

public class Foo {
    @Length(min = 6, max = 30)
    @Pattern(regexp = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*)", message = "{error.password.too_simple}")
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

As you see, there is one field 'password' and two validate annotations. But, in some situations, I want that only one should be applied, not both. For example: if I have empty string: "" I want, that only one restriction be applied: the first (@Length), but in my situation applied both restrictions. What should I do, how can I applied only one restriction in the situation?


Solution

  • You could assign the constraints to different validation groups and validate them using a group sequence, e.g. by re-defining the default group sequence for Foo:

    public interface EmptyChecks {}
    
    @GroupSequence( { EmptyChecks.class, Foo.class } )
    public class Foo {
        @Length(min = 6, max = 30, groups=EmptyChecks.class)
        @Pattern(regexp = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*)", message = "{error.password.too_simple}")
        private String password;
    
        //...
    }
    

    Now the @Pattern constraint will only be validated if the @Length constraint is valid.

    Your specific case might also be solved by accepting an empty value (^$) in the regular expression of the @Password constraint:

    @Pattern(regexp = "(^$|(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).*)", message = "")
    

    That way both constraints will be validated but only the @Length constraint will fail for an emtpy input value.