Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate regex validation on fields doesn't work

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?

like image 275
silent-box Avatar asked Sep 10 '15 14:09

silent-box


2 Answers

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;
like image 93
tmarwen Avatar answered Nov 14 '22 21:11

tmarwen


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.

like image 43
Steve Chambers Avatar answered Nov 14 '22 23:11

Steve Chambers