JSR验证@Pattern允许使用空值

问题描述

当我使用@Pattern注释字段时

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

如果JSON包含此字段,其值为 null ,则我希望此正则表达式失败并因此无效。

如果JSON不包含此字段,则可以通过验证。

如何实现?

解决方法

对于字符串,我通常使用@NotBlank表示非空字符串,但是我不确定100%不允许使用空条目,但在这种情况下,请使用@NotNull注释。

编辑:我正在寻找一个示例,并且是从一个旧项目中得到的:

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

如您所见,即使我在那里有模式,我也使用NotNull和NotBlank。