Multiple Regex @Pattern's for 1 Field?

Chris Harris picture Chris Harris · Apr 25, 2013 · Viewed 15.9k times · Source

I was attempted to apply multiple @Pattern annotations to a single field:

@Pattern(regexp = "(?=.*[0-9])", message = "Password must contain one digit.")
@Pattern(regexp = "(?=.*[a-z])", message = "Password must contain one lowercase letter.")
@Pattern(regexp = "(?=.*[A-Z])", message = "Password must contain one uppercase letter.")
@Pattern(regexp = "(?=\S+$)", message = "Password must contain no whitespace.")
private String password;

However, I cannot do this. I want individual messages per violated regex constraint on the password field. Is this possible?

My alternative is to use JSF 2.0 f:validatorRegex tags.

Answer

Gunnar picture Gunnar · Apr 26, 2013

You can use the inner @List annotation of @Pattern:

@Pattern.List({
    @Pattern(regexp = "(?=.*[0-9])", message = "Password must contain one digit."),
    @Pattern(regexp = "(?=.*[a-z])", message = "Password must contain one lowercase letter."),
    @Pattern(regexp = "(?=.*[A-Z])", message = "Password must contain one uppercase letter."),
    @Pattern(regexp = "(?=\\S+$)", message = "Password must contain no whitespace.")
})
private String password;