PatternRegex

Validate a username

Check that a signup username starts with a letter and uses only letters, digits or underscores, 3 to 16 characters long.

Last updated

Pattern
^[a-zA-Z][a-zA-Z0-9_]{2,15}$
Open in Regex Tester & Builder

Matches

  • john_doe123
  • abc
  • User_1

Doesn’t match

  • ab
  • 1abc
  • user-name

Why it’s written this way

The anchors ^ and $ pin the pattern to the whole field, so a signup form can't accept a value just because the start looks fine — an anchored validator has to consume every character, not just a promising substring.

[a-zA-Z] forces the first character to be a letter, then [a-zA-Z0-9_]{2,15} allows 2 to 15 more letters, digits or underscores, which caps the total length at 16 characters — a common ceiling for names that also get used as URL slugs or @handles.

Edge cases to know

  • It only recognizes ASCII letters — a name typed in Cyrillic or Devanagari script is rejected outright, which may not match a product's internationalization goals.
  • It says nothing about whether the username is already taken, or whether it collides case-insensitively with an existing one — that check belongs server-side, not in the regex.
  • Reserved words like 'admin' or 'root' pass the pattern fine; blocking those needs a separate lookup, not a tighter regex.

Related in Patterns