简体   繁体   中英

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?

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.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM