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?
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:Now the
@Patternconstraint will only be validated if the@Lengthconstraint is valid.Your specific case might also be solved by accepting an empty value (
^$) in the regular expression of the@Passwordconstraint:That way both constraints will be validated but only the
@Lengthconstraint will fail for an emtpy input value.