Regex for username validation
A typical username rule: 3 to 16 characters, starting with a letter, followed by letters, digits or underscores. The lookahead checks the length in one place, so you can change it without rewriting the character rules.
The pattern
/^(?=.{3,16}$)[A-Za-z][A-Za-z0-9_]*$/gmThe tester opens with this pattern and the examples below already loaded. Nothing you type is uploaded.
How it works
(?=.{3,16}$)- Lookahead: the whole value must be 3 to 16 characters long. It does not consume any characters.
[A-Za-z]- The first character must be a letter.
[A-Za-z0-9_]*- Any number of letters, digits or underscores after it.
^ … $- The pattern must cover the entire value.
Examples
Matches
john_doeUser123abc
Does not match
ab1useruser nameuser@namethis_username_is_too_long
Use it in JavaScript
const re = /^(?=.{3,16}$)[A-Za-z][A-Za-z0-9_]*$/gm;
// Find every match in a block of text
const found = text.match(re);
// Validate that a whole value matches (no stray characters around it)
const exact = new RegExp('^(?:' + re.source + ')$', re.flags.replace('g', ''));
const isValid = exact.test(value);Limits and tips
- Change the 3 and 16 in {3,16} to set your own length limits.
- To allow dots or hyphens add them in the class, for example [A-Za-z0-9._-]. Decide whether they may start or end the name, or appear twice in a row.
- To forbid a trailing underscore, end with a letter or digit: ^(?=.{3,16}$)[A-Za-z][A-Za-z0-9_]*[A-Za-z0-9]$.
- Regex only checks the shape. Check uniqueness, reserved words (admin, root) and offensive names on the server.
Frequently asked questions
What is a good regex for a username?
^(?=.{3,16}$)[A-Za-z][A-Za-z0-9_]*$: 3 to 16 characters, starting with a letter, with only letters, digits and underscores.
Should usernames be case-sensitive?
Most sites treat them as case-insensitive. Store a lowercase copy for comparison so that John and john are not two accounts.