Kevin Rave Kevin Rave - 5 months ago 74
Java Question

@Pattern for alphanumeric string - Bean validation

I have a variable name in a bean. I want to add

validation to accept only alphanumeric.

Currently, I have this one.

@Pattern(regexp = "{A-Za-z0-9}*")
String name;

But the error is
Invalid regular expression.

I tried
. But this is not working either. No errors though. It shows any valid input as failed.


Do you try this pattern: ^[A-Za-z0-9]*$

or ^[A-Za-z0-9]+$ to avoid void entries.

If you want to check that a string contains only specific characters, you must add anchors (^ for begining of the string, $ for end of the string) to be sure that your pattern matches all the string.

Curly brackets are only to write a quantity, example: i want two a:
You can't put letters inside. The only cases you can meet letters inside curly brackets are when you use unicode character classes: \p{L}, \p{Greek}, \p{Arabian}, ...