I've got a simple regex, which should match only letters and numbers in last 4 chars of string:
([a-zA-Z0-9]{4}$)
It works perfectly in online tester, but doesn't match if i use it with hibernate validation annotation on field:
@NotNull
@Length(min = 4, max = 25)
@Pattern(regexp = "([a-zA-Z0-9]{4}$)")
private String test;
For example, it returns false for 1234.5678-abC2
string
Could you help me?
For future visitors, I would add the response of @hofan41 provided in the main OP comment.
You are assuming that the
@Pattern
annotation will return true if a substring regex match passes. If it isn't working then your assumption may not be true. Try adding .* in the beginning of your pattern string.
In such a manner, the bean property validation annotations will look as follows:
@NotNull
@Length(min = 4, max = 25)
@Pattern(regexp = ".*([a-zA-Z0-9]{4}$)")
private String test;
The pattern matches against the entire region as can be seen in the following PatternValidator code:
public boolean isValid(CharSequence value, ConstraintValidatorContext constraintValidatorContext) {
if ( value == null ) {
return true;
}
Matcher m = pattern.matcher( value );
return m.matches();
}
...And from the documentation for Matcher.matches:
Attempts to match the entire region against the pattern.
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