Reputation: 190
I am trying to apply validation for telephone number, we can allow it to be null and empty. But it has to be the size of 10 characters only whenever entered.
this is the code I have
@Size(max=10,min=10, message = "mobile no. should be of 10 digits")
private String mobile;
when I pass no value at all, the null is accepted, but when I pass an empty string like this.
"mobile":""
It gives me error that "mobile no. should be of 10 digits".
Upvotes: 3
Views: 5560
Reputation: 18430
To accept blank value string containing white space or exact 10 characters try this
@Pattern(regexp = "\\s*|.{10}")
private String mobile;
To accept only empty string or exact 10 characters
@Pattern(regexp = "|.{10}")
private String mobile;
Here,
\\s*
- \\s
for a whitespace character and *
for occurs zero or more times
|
- Alternation (OR)
.{10}
- .
for matches any character and {10}
for occurs 10 number of times
Try to explore Regular expressions in Java
Upvotes: 5
Reputation: 928
You can also combine @Nullable
with @Size
@Nullable
@Size(max=10,min=10, message = "mobile no. should be of 10 digits")
private String mobile;
Upvotes: 3