Reputation: 69
@Pattern(regexp = "^[a-zA-Z0-9_-]*$", message = "Only alpha-numeric characters are allowed")
private String recipientId;
I want to allow only alpha-numeric characters but above validation does not work as i expect. It allows a request which has a plus sign (+) to pass through
Upvotes: 0
Views: 2606
Reputation: 20065
When using brackets, hyphen is special character for defining range so you should escape it, if you want to match "-".
The regexp should looks like
[a-zA-Z0-9_\\-]*
Note : After testing it seems that you can use hyphen without escaping it when using brackets.
I would prefer this way (\\w|-)*
\w A word character: [a-zA-Z_0-9]
The issue is maybe not on the regexp but maybe on the way the validation annotation is used. You can use the annotation on the field directly or on the getter but not on both. Are you sure that you always follow the same coding pattern for all annotations?
Finally do you use the annotation @Valid
to actually validate your input?
Upvotes: 1