Chris
Chris

Reputation: 89

@Pattern annotation not working if the input is blank

Please refer to the below controller code:-

@GetMapping("/fetch)
void fetchData( @RequestParam 
                 @Pattern(regexp="(^$|[0-9]{10})",message = "Mobile number must be 10 digits")
                 String mobileNumber)
{
 .........//some functionality
}

Now if I call the above API:-

http://localhost:8080/fetch?mobileNumber=123456789

I am getting the error message:- Mobile Number must be 10 digits.

But If I hit the same API with empty mobile Number, the pattern validation is not working and it is proceeding in to the method. so If I call the below endpoint:-

http://localhost:8080/fetch?mobileNumber=

The validation is not working and I am not getting the error message.

Can you please tell me what is the issue, why is the error message not triggering for the second request? Am I missing something related to Regex?

Upvotes: 0

Views: 36

Answers (1)

M. Deinum
M. Deinum

Reputation: 125292

Accepts CharSequence. null elements are considered valid.

Above is a quote from the JavaDoc of the @Pattern annotation.

Because @Pattern allows empty/null values. To prevent those you would need an additional @NotEmpty on the field.

Upvotes: 1

Related Questions