Validate Username (Rules + Edge Cases)

easy
By FrontendAtlas Editorial · Updated Oct 10, 2026
Implement validateUsername(name) to enforce common username rules and handle edge cases safely. Rules: 3–16 chars, lowercase letters/digits/underscore only, must start with a letter, no consecutive underscores, and no trailing underscore.

Arguments

  • name: string — The username to validate.

Returns

boolean — True if valid; otherwise false.

Solution idea

Validate step-by-step: type guard, length check, allowed characters, and underscore rules. This makes edge cases explicit and tests easy to reason about.

Examples
validateUsername('alice_1') // => true

validateUsername('2cool')   // => false (must start with a letter)

validateUsername('bob__x')  // => false (no consecutive underscores)