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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With