Coding problem · Easy · Basics

Valid Username

Easy Algorithms & data structures

A username is valid when:

  • it is 3 to 16 characters long,
  • it contains only letters, digits and underscores (_),
  • it starts with a letter.

Return true if name is valid.

Example 1

Input: name = "ana_dev"
Output: true

Example 2

Input: name = "1ana"
Output: false
Explanation: Starts with a digit.

Example 3

Input: name = "a b"
Output: false

Hints

Hint 1

Check each rule separately and return false as soon as one fails.

Hint 2

A regular expression can express all three rules in one line: ^[A-Za-z][A-Za-z0-9_]{2,15}$

Write and run your solution

Loading the editor… (JavaScript is required to run code in your browser.)

Solution and explanation

Show the solution

Time O(n) · Space O(1)

Either check the rules in code (length, first character, allowed characters) or use one regular expression: a letter followed by 2 to 15 letters, digits or underscores.

Reference solution

function isValidUsername(name) {
  return /^[A-Za-z][A-Za-z0-9_]{2,15}$/.test(name);
}

Was this page helpful?