Regex for Username
This regex matches usernames between 3 and 20 characters containing only letters, numbers, underscores, and hyphens. This is one of the most common username format policies used across web applications. It prevents special characters that could cause issues in URLs, file paths, or SQL queries while still allowing readable, flexible usernames.
^[a-zA-Z0-9_-]{3,20}$ What is the regex pattern for Username?
The regex pattern for Username is ^[a-zA-Z0-9_-]{3,20}$. This regex matches usernames between 3 and 20 characters containing only letters, numbers, underscores, and hyphens. This is one of the most common username format policies used across web applications. It prevents special characters that could cause issues in URLs, file paths, or SQL queries while still allowing readable, flexible usernames. This pattern is commonly used for user registration forms and profile url slugs.
Test Examples
john_doe john_doe dev-user-42 dev-user-42 ab Common Uses
- ✓ User registration forms
- ✓ Profile URL slugs
- ✓ Mention systems (@username)
- ✓ Access control
Variations
Must start with letter
^[a-zA-Z][a-zA-Z0-9_-]{2,19}$ First character must be a letter
Lowercase only
^[a-z0-9_-]{3,20}$ Enforces lowercase for URL-friendly usernames
With dots
^[a-zA-Z0-9._-]{3,20}$ Also allows periods (like GitHub)
Frequently Asked Questions
Why limit username length to 3-20 characters?
A minimum of 3 prevents meaningless usernames, and a maximum of 20 keeps them readable in UIs and URLs. These are common defaults, but you can adjust them to your application's needs.
Should usernames be case-sensitive?
Most applications treat usernames as case-insensitive to prevent confusion (e.g., JohnDoe vs johndoe). Store the original casing for display but normalize to lowercase for uniqueness checks.
Why not allow spaces or special characters?
Restricting to alphanumeric characters, underscores, and hyphens ensures usernames are safe for URLs, file paths, command-line arguments, and database queries without requiring escaping.