JSR Validation @Pattern allowing null values

Viewed 730

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?

1 Answers

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.

Related