I'm using the Pattern
validation from javax.validation.constratins
to validate a field. The string:
null
or empty ORI managed to validate for the seven digits but I can't figure out how to additionally validate that this field may be empty.
@Getter
@Setter
public class MyRestRequest {
@Pattern(regexp = "\\d{7}")
private String someString;
}
Because for Pattern null
is considered to be valid, problem boils down to construct regular expression that matches to empty String or to seven digits. Typically for empty string one uses ^$
(beginning and end of the line).
In this case also ^|\\d{7}
and $|\\d{7}
or even |\\d{7}
would work, but ^$|\\d{7}
is more typical:
@Pattern(regexp = "^$|\\d{7}")
public String someString;