I want to create a class in java for username validation using Regex. A username is considered valid if all the following constraints are satisfied:
- The username consists of 8 to 30 characters inclusive. If the username consists of less than or greater than characters, then it is an invalid username.
- The username can only contain alphanumeric characters and underscores (_). Alphanumeric characters describe the character set consisting of lowercase characters [a-z], uppercase characters [A-Z], and digits [0-9].
- The first character of the username must be an alphabetic character, i.e., either lowercase character [a-z] or uppercase character [A-Z].
I have tried an expression like:
^[a-zA-Z0-9_]{8-30}$
This is giving me result as invalid for all usernames. I expect the output of Samantha_21 to be valid.
Your regex has a typo and an omission. The typo is that the range limits should be separated by a comma. The omission is that you don't check the first character separately:
^[a-zA-Z][a-zA-Z0-9_]{7,29}$
The range is decreased by one to accommodate the fixed first character.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With