@Pattern for alphanumeric string - Bean validation

I have a variable name in a bean. I want to add @Pattern validation to accept only alphanumeric characters.

I currently have this one.

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

But the error is Invalid regular expression. I tried [A-Za-z0-9] . But that doesn't work either. However, there are no errors. It shows any valid input as not completed.

+7
java regex annotations bean-validation
source share
2 answers

Try this template: ^[A-Za-z0-9]*$

or ^[A-Za-z0-9]+$ to avoid empty results.

If you want to verify that the string contains only certain characters, you must add anchors ( ^ to start the string, $ to the end of the string) to make sure your pattern matches the entire string.

Curly braces should only write a quantity, for example: I want two a :
a{2}
You cannot insert letters inside. The only cases where you can find letters inside curly braces are when you use the Unicode character classes: \p{L} , \p{Greek} , \p{Arabian} , ...

+20
source share

In addition, you can use a character class that can be used in curly braces, namely in Alnum. For example, for an alphanumeric character between 1 and 32 characters long, inclusive:

 @Pattern(regexp = "^[\\p{Alnum}]{1,32}$") 

see https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

+3
source share

All Articles