4

I am trying to develop a simple REGEX in Java with pattern like that :

@Pattern(regexp = "[a-zA-Z]{2}[0-9]{1}[2-8]{1}" , message = "The format is invalid")

but this message is still displayed when the field is empty, so i want to show this message only when the field is not empty (i want that the field is will be not required).

Thank you.

BNJ
  • 108
  • 1
  • 8

2 Answers2

3

Try using the following regex, which matches both your expected string and empty string:

[a-zA-Z]{2}[0-9]{1}[2-8]{1}|^$

Java code:

@Pattern(regexp = "[a-zA-Z]{2}[0-9]{1}[2-8]{1}|^$", message = "The format is invalid")
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
2

You could make your whole pattern optional using a non capturing group (?:...)?to match either an empty string or the whole pattern.

Note that you can omit the {1} part.

^(?:[a-zA-Z]{2}[0-9][2-8])?$

Regex demo

@Pattern(regexp = "^(?:[a-zA-Z]{2}[0-9][2-8])?$" , message = "The format is invalid")
The fourth bird
  • 154,723
  • 16
  • 55
  • 70