JAVASCRIPT

Validate Alphanumeric Usernames (with dots/underscores)

Create a regex to validate usernames, allowing alphanumeric characters, underscores, and periods, with specific length constraints for web applications.

function isValidUsername(username) {
  // Allows alphanumeric, dots, and underscores. Length 3-20.
  const usernameRegex = /^[a-zA-Z0-9._]{3,20}$/;
  return usernameRegex.test(username);
}

console.log(isValidUsername("john_doe123")); // true
console.log(isValidUsername("user.name")); // true
console.log(isValidUsername("us")); // false (too short)
console.log(isValidUsername("user_name_with_many_chars_and_too_long")); // false (too long)
console.log(isValidUsername("user-name")); // false (invalid character '-')
How it works: The `isValidUsername` function validates usernames against a defined pattern: `^[a-zA-Z0-9._]{3,20}$`. This regex ensures that usernames begin and end with the specified characters (`^` and `$`). It permits uppercase and lowercase letters (`a-zA-Z`), digits (`0-9`), dots (`.`), and underscores (`_`). The `{3,20}` quantifier enforces a minimum length of 3 characters and a maximum of 20 characters. This is a common pattern for user-friendly username requirements in web applications.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs