Search code examples
validationjax-rsbean-validation

JAX-RS validation for string which may be empty or must have n digits


I'm using the Pattern validation from javax.validation.constratins to validate a field. The string:

  • may be null or empty OR
  • it must have exactly seven digits.

I 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;

}

Solution

  • 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;