Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple @Pattern behaving like OR operation

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.

like image 255
jlanza Avatar asked Nov 28 '25 13:11

jlanza


2 Answers

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.

like image 85
Federico Piazza Avatar answered Nov 30 '25 02:11

Federico Piazza


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.

like image 24
Hardy Avatar answered Nov 30 '25 03:11

Hardy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!