Reputation: 34
Working:
@Pattern(regexp = "^(?=.*\\d)(.{8,})$")
private String str;
Never matches (no matter if str is valid or not):
@Pattern(regexp = "^(?=.*\\d)(.{8,30})$")
private String str;
The only difference in the second pattern is the max length (30) beeing specified.
The second regex works though if I use String.matches()
:
String regex = "^(?=.*\\d)(.{8,30})$";
String validString= "12345678"; // 8 chars
assertTrue(validString.matches(regex));
String invalidString = "123456789012345678901234567890A"; // 31 chars
assertFalse(invalidString.matches(regex));
I also successfully tried the second regex on https://regex101.com/ ...
Anyone got an idea how I could change the second regex for it to work with the @Pattern
annotation?
I'm using spring-boot 3.2.3, java 17 and gradle 7.5.1
Thanks in advance
Upvotes: -1
Views: 1428
Reputation: 34
Turns out the error was caused by hibernate validation during persistence time. I was encrypting the string just before saving it, that's why the regex did not work during persistence action anymore and I got confusing results.
Solution: add
spring.jpa.properties.jakarta.persistence.validation.mode=none
to properties. This will prevent validation during db actions. See hibernate documentation: https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-checkconstraints-orm-hibernateevent
Upvotes: 0