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

^(?=.{3,30}$)[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$

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 123 or _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

const usernameRegex = /^(?=.{3,30}$)[A-Za-z][A-Za-z0-9]*(?:[._-][A-Za-z0-9]+)*$/;
const isValidUsername = (username) => usernameRegex.test(username);

Test Cases

UsernameValid
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