Ahmad Amin
Ahmad Amin

Reputation: 19

Regex to validate username in java

username must not contain special symbols including ( " . & * ^ ) Username can only consists of letters, numbers(digits) and underscore. Username can only start with letters and underacore. Length must be (6-20)

Here this regex I'm using but it allowing username to start with * , & , ^

Pattern.matches("^(\\D)([a-zA-Z0-9_]){6,20}"

Upvotes: 0

Views: 305

Answers (1)

Mureinik
Mureinik

Reputation: 311188

The first character in your regex is "not a digit", which would allow special characters. Instead, you should limit it to letters or underscore. In addition, note you have an off by one error, since your range (6,20) doesn't count the first character:

Pattern.matches("^[a-zA-Z_]([a-zA-Z0-9_]){5,19}")

Upvotes: 2

Related Questions