29

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

Currently, I 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 this is not working either. No errors though. It shows any valid input as failed.

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
Kevin Rave
  • 13,876
  • 35
  • 109
  • 173

2 Answers2

48

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

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

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

Curly brackets are only used to express a repetition, example: if I want two a:
a{2}
You can't put letters inside. The only situation where you can find letters enclosed between curly brackets is when you use UNICODE character classes: \p{L} (L for Letters), \p{Greek}, \p{Arabian}, ...

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
7

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

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

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

  • This is as per specification but doesnt work. @Pattern(regexp = "^[\\p{Alnum}]$") – Dinesh Jun 15 '18 at 23:16
  • @Dinesh, I think you were expecting it to validate a mandatory Alphanumeric. In other words, you expected this to block only alphabets or only numbers. That's not the intended behaviour. It allows only alphabets, only numbers and alphanumeric strings. – Zooter Nov 28 '19 at 07:22