JSR Validation @Pattern allowing null values

2k views Asked by At

When I annotate a field with @Pattern

@Pattern(regexp="someRegexp")
public String name;

If the JSON contains this field, with value as null, then I expect this regex to fail and thus invalid.

if the JSON does NOT contain this field, then it is fine for the validation to pass.

How to achieve this?

2

There are 2 answers

3
Sergio Garrido Domínguez On

To Strings, I usually use @NotBlank for not empty strings, but im not sure at 100% that it doesnt allow null entries, but, in this case, use @NotNull annotation.

Edit: I was looking for an example and I got this from an old project:

@NotNull
@NotBlank
@Pattern(regexp = "somePattern")
public String getEmail() {
    return this.email;
}

As you can see, I use NotNull and NotBlank even though I have a pattern there.

0
KMC On

I know it's 3 year old question, but for the sake of those who stumble onto this question like myself, the only option I can think of is, to use @NotNull in conjunction with @Pattern. Use the pattern to handle the empty string.