🔍Regex Recipes
Username (Safe)
Safe username validation with letters, numbers, dots, underscores, and hyphens with length rules.
Pattern
^[a-zA-Z0-9._-]{3,20}$Explanation
Allows alphanumeric characters plus dots, underscores, and hyphens. Length 3-20 characters.
Examples
Valid
Input
john_doe
Output
✓ Match
Valid
Input
user.name
Output
✓ Match
Valid
Input
user-123
Output
✓ Match
Invalid - too short
Input
ab
Output
✗ No match
Invalid - special char
Input
user@name
Output
✗ No match
Code Examples
JavaScript
const usernameRegex = /^[a-zA-Z0-9._-]{3,20}$/;
function validateUsername(username) {
if (!usernameRegex.test(username)) {
return 'Username must be 3-20 characters, letters, numbers, dots, underscores, hyphens only';
}
// Additional checks
if (username.startsWith('.') || username.endsWith('.')) {
return 'Username cannot start or end with a dot';
}
return null; // valid
}Try it Now
💡 Tips
- Add case-insensitive check for duplicates
- Consider blocking profanity and reserved words
- Display requirements clearly to users
- Allow users to change usernames later
⚠️ Common Pitfalls
- Does not prevent consecutive dots or special chars
- May want to disallow starting/ending with special chars
- Consider reserved usernames (admin, root, etc.)
- Length limits should match your database constraints