Reputation: 1472
I need set validation on input of String field. This field should be an empty or between 5
to 10
characters. But if I set validation like this:
@Size(min=5, max=10)
private String couponCode;
It won't pass @Valid
when the value is empty. How can I achieve that?
Upvotes: 3
Views: 3338
Reputation: 48133
You can set a pattern to accept blank values or 5
to 10
characters:
@Pattern(regexp = "|.{5,10}")
private String couponCode;
Here we used Alternation, the |
, to tell the validator to consider the passed value valid, if either empty string or .{5,10}
patterns were matched.
If you consider blank values as empty strings, use the following pattern:
@Pattern(regexp = "\\s*|.{5,10}")
private String couponCode;
Upvotes: 4