zzheads zzheads - 1 year ago 39
Java Question

How set validation on size of string = 0 or min=5, max=10?

I need set validation on input of String field. This field should be an empty or between

characters. But if I set validation like this:

@Size(min=5, max=10)
private String couponCode;

It won't pass
when the value is empty. How can I achieve that?

Answer Source

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;