Username Validation Regular Expression
Username validation usually balances readability, uniqueness, and compatibility with URLs or login systems. This pattern accepts usernames that start with a letter, are 3 to 30 characters long, use only ASCII letters and digits plus ., _, and -, and do not allow separators to repeat or appear at the end.
Recommended Solution
Explanation
^- Start of the string.(?=.{3,30}$)- Enforces a total length between 3 and 30 characters.[A-Za-z]- The username must start with an ASCII letter.[A-Za-z0-9]*- Allows zero or more letters or digits immediately after the first character.(?:[._-][A-Za-z0-9]+)*- Allows segments separated by a single dot, underscore, or hyphen, followed by one or more letters or digits.$- End of the string.
Notes
- This is a format check only. You still need an availability check to know whether a username is already taken.
- The pattern is intentionally ASCII-only. If you need international usernames, use a Unicode-aware strategy instead of widening this regex casually.
- Requiring a leading letter avoids usernames like
123or_admin, which some systems treat differently. - If your product allows email-style identifiers, consider using a separate email validation flow instead of overloading the username field.
Implementation
Test Cases
| Username | Valid |
|---|---|
| alice | |
| alice_123 | |
| Alice-01 | |
| john.doe | |
| a1_b2-c3 | |
| ab | |
| 1alice | |
| _alice | |
| alice_ | |
| alice..doe | |
| alice__doe | |
| alice--doe | |
| alice.-doe | |
| alice doe | |
| alice@doe | |
| (empty string) | |
| abcdefghijklmnopqrstuvwxyzabcde | |
| álvaro |