Skip to main content
AllDevToolsHub
Back to all patterns

Username Validation

Validation

Validates usernames: 3–20 characters, letters, numbers, underscores, and hyphens only.

/^[a-zA-Z0-9_-]{3,20}$/

How it works

This pattern enforces a common username policy: alphanumeric characters plus underscores and hyphens, with a minimum of 3 and maximum of 20 characters. No spaces or special characters are allowed.

Test Cases

Should Match

  • john_doe
  • user-123
  • Alice99

Should NOT Match

  • ab
  • this_username_is_way_too_long_for_the_limit
  • has space

Quick Summary

Validates usernames: 3–20 characters using letters, numbers, underscores, and hyphens. No spaces or other special characters. Adjust the length range {3,20} to match your platform policy.

Key Takeaways

Key Takeaways

  • Allows letters (upper and lower), digits, underscores, and hyphens
  • Minimum 3 characters, maximum 20, adjust to your policy
  • Does not prevent reserved words like admin or root, check those separately
  • Case-sensitive by default, normalize to lowercase before storage if needed
Use Cases

When to use it

  • Registration form username validation
  • Validating @mentions in social or comment systems
  • Checking API key names or resource identifiers
Watch out

Common Mistakes

  • Not reserving common usernames like admin, root, support
  • Allowing usernames that look like email addresses, add an exclusion if needed
FAQ

Username Validation, Frequently Asked

Should usernames be case-sensitive?

Most platforms normalize to lowercase to prevent confusion between User and user. Store lowercase and compare case-insensitively.

How do I check username availability?

After format validation, query your database with a case-insensitive unique check.