3

From Multiple Regex @Pattern's for 1 Field? I see how to add multiple patterns, but those are acting as an AND operation.

Is there any way to apply an OR type?

I want to check for an URL pattern and in this sense there are two possiblities: - domain based - IP address based

Both are similar but different so I want to include two patterns.

Community
  • 1
  • 1
jlanza
  • 1,208
  • 3
  • 23
  • 43

2 Answers2

3

Following the example post on the link you provided, you could leverage regex OR, so instead of putting multiple patterns working like AND like this:

@Pattern.List({
    @Pattern(regexp = "(?=.*[0-9])", message = "Password must contain one digit."),
    @Pattern(regexp = "(?=.*[a-z])", message = "Password must contain one lowercase letter.")
})
private String password;

You could change it to use one single pattern with regex alternation working as OR:

@Pattern(regexp = "(?=.*[0-9])|(?=.*[a-z])", message = "Password is invalid")
private String password;

I cannot test this code since I don't have a project, but I just use the alternation patterns that works in all regex engines.

Federico Piazza
  • 30,085
  • 15
  • 87
  • 123
  • I've also thought on your approach but as the regexs are quite long, I was looking for something more "clean". thanks anyway. – jlanza Jun 08 '16 at 08:22
  • @jlanza well, that's a different question related to how to shorten a regex. If the answers posted in this question solve your issue, then you should mark your question as resolved and open a new one. Related to shorten your regex, then you could use then this one `(?=.*([0-9]|[a-z]))` – Federico Piazza Jun 08 '16 at 14:48
  • Thanks for your response. The question was generally related to regex OR and you answered correctly. With my comment I was just saying the this was already in my plans, but I was looking for a Pattern.List but with OR included in it, so I can get different messages, etc. – jlanza Jun 08 '16 at 19:59
1

One solution is to write a composed constraint, eg MyURLPattern which internally uses the Hibernate specific feature of "Boolean composition of constraints". In this case you need to also add the @ConstraintComposition(OR) annotation to your composing constraint.

The caveat is that this solution won't be portable between Bean Validation providers.

Hardy
  • 18,659
  • 3
  • 49
  • 65