Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Pattern for alphanumeric string - Bean validation

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.

like image 913
Kevin Rave Avatar asked Jul 05 '13 04:07

Kevin Rave


People also ask

Which special sequence is used to check whether an alphanumeric character is present in the string or not?

The idea is to use the regular expression ^[a-zA-Z0-9]*$ , which checks the string for alphanumeric characters. This can be done using the Regex. IsMatch() method, which tells whether this string matches the given regular expression.

What is alphanumeric string?

An alphanumeric string is a string that contains only alphabets from a-z, A-Z and some numbers from 0-9. Examples: Input: str = “GeeksforGeeks123”

How do I allow special characters in regex?

You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/. To know more about regex ,watch this videos. You can use this regex /^[ A-Za-z0-9_@./#&+-]*$/.


1 Answers

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}, ...

like image 129
Casimir et Hippolyte Avatar answered Sep 20 '22 18:09

Casimir et Hippolyte