How to allow a field to be blank in spring boot?

Viewed 2118

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".

2 Answers

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

You can also combine @Nullable with @Size

@Nullable
@Size(max=10,min=10, message = "mobile no. should be of 10 digits")
private String mobile;
Related