1

I am trying to validate a String in Java to see if it matches the randomUUID format using the following regex

^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$

Now this works fine and picks up invalid strings and so on – however, if I pass a null String to the regex, it returns true, so when I perform validation on the Pattern annotation, no constraint violations are reported. Is this expected behaviour, since the String is null it is not performing any validation?

As a way around this, on the getter method that I have annotated with the Pattern annotation, I have used this

return id != null ? id : "null"

This works, however it seems a bit... hacky to me :)

SQB
  • 3,926
  • 2
  • 28
  • 49
KingTravisG
  • 1,316
  • 4
  • 21
  • 43

1 Answers1

4

If you want to exclude nulls, use a 'not null' annotation, such as @NotNull.


PatternValidator returns true if the argument is null (a weird choice, IMHO); it says so right in the source. I've seen different versions, and they all did this, so it's really part of the contract (and should be documented better).

public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
    if ( value == null ) {
        return true;
    }
    Matcher m = pattern.matcher( value );
    return m.matches();
}
Community
  • 1
  • 1
SQB
  • 3,926
  • 2
  • 28
  • 49