Overview
The isUsername() function validates usernames according to customizable rules. It supports length constraints, special character restrictions, space handling, and blocked username lists to enforce your application’s username policies.
Common Use Cases
- User registration and account creation
- Username availability checks
- Profile name validation
- Social platform username validation
- Gaming platform username rules
Function Signature
isUsername(username, options)
Parameters
The username to validate.
Configuration options for username validation.Minimum username length in characters.
Maximum username length in characters.
options.allowSpecialChars
Whether to allow special characters like !@#$%^&*(),.?":{}|<>.
Whether to forbid spaces in usernames.
options.forbidStartingNumber
Whether to forbid usernames that start with a number.
List of blocked usernames (case-insensitive). Useful for reserving admin names, preventing profanity, etc.
Whether to return detailed validation information instead of a boolean.
Return Value
When details is false: Returns true if valid, false otherwise.When details is true: Returns an object with the following properties:Whether the username is valid.
Array of validation error messages, or null if valid.
The trimmed username that was validated.
Examples
Basic Username Validation
Simple Validation
Custom Length
Allow Special Characters
import { isUsername } from 'validauth';
// Valid usernames
isUsername('john_doe');
// Returns: true
isUsername('alice123');
// Returns: true
isUsername('user-name');
// Returns: true
// Invalid usernames
isUsername('ab');
// Returns: false (too short)
isUsername('123user');
// Returns: false (starts with number)
isUsername('user name');
// Returns: false (contains space)
import { isUsername } from 'validauth';
// Custom length requirements
isUsername('ab', {
minLength: 2,
maxLength: 20
});
// Returns: true
// Very short usernames for gaming
isUsername('x', {
minLength: 1,
maxLength: 10
});
// Returns: true
import { isUsername } from 'validauth';
// By default, special characters are not allowed
isUsername('user@name');
// Returns: false
// Allow special characters
isUsername('user@name!', {
allowSpecialChars: true
});
// Returns: true
Blocking Reserved Usernames
import { isUsername } from 'validauth';
// Block reserved and admin usernames
const blockedNames = [
'admin',
'root',
'administrator',
'moderator',
'system',
'support',
'api',
'null',
'undefined'
];
isUsername('admin', {
blockedUsernames: blockedNames
});
// Returns: false
isUsername('Admin', {
blockedUsernames: blockedNames
});
// Returns: false (case-insensitive)
isUsername('regular_user', {
blockedUsernames: blockedNames
});
// Returns: true
Detailed Validation
import { isUsername } from 'validauth';
// Get detailed validation results
const result = isUsername('john_doe_123', {
details: true
});
console.log(result);
/* Returns:
{
valid: true,
errors: null,
username: 'john_doe_123'
}
*/
// Invalid username with details
const result2 = isUsername('123user name!', {
details: true
});
console.log(result2);
/* Returns:
{
valid: false,
errors: [
'Username cannot contain spaces',
'Username cannot contain special characters',
'Username cannot start with a number'
],
username: '123user name!'
}
*/
import { isUsername } from 'validauth';
function validateRegistrationUsername(username) {
const blockedUsernames = [
'admin', 'root', 'system', 'api',
'moderator', 'administrator', 'support'
];
const result = isUsername(username, {
minLength: 3,
maxLength: 20,
allowSpecialChars: false,
forbidSpaces: true,
forbidStartingNumber: true,
blockedUsernames: blockedUsernames,
details: true
});
if (!result.valid) {
return {
success: false,
message: 'Invalid username',
errors: result.errors
};
}
return {
success: true,
username: result.username
};
}
// Usage
const validation = validateRegistrationUsername('john_doe');
if (validation.success) {
console.log('Username is available:', validation.username);
} else {
console.error('Validation errors:', validation.errors);
}
import { isUsername } from 'validauth';
function validateGamingUsername(username) {
return isUsername(username, {
minLength: 3,
maxLength: 16,
allowSpecialChars: false,
forbidSpaces: true,
forbidStartingNumber: false, // Allow numbers at start
details: true
});
}
// Valid gaming usernames
validateGamingUsername('Player123').valid; // true
validateGamingUsername('xXProGamerXx').valid; // true
validateGamingUsername('ninja_master').valid; // true
import { isUsername } from 'validauth';
function validateSocialUsername(username) {
return isUsername(username, {
minLength: 3,
maxLength: 30,
allowSpecialChars: false,
forbidSpaces: true,
forbidStartingNumber: true,
details: true
});
}
// Valid social media usernames
validateSocialUsername('john_doe').valid; // true
validateSocialUsername('alice.smith').valid; // true
validateSocialUsername('bob-jones').valid; // true
Display Name (More Permissive)
import { isUsername } from 'validauth';
function validateDisplayName(name) {
return isUsername(name, {
minLength: 1,
maxLength: 50,
allowSpecialChars: true,
forbidSpaces: false, // Allow spaces
forbidStartingNumber: false, // Allow numbers at start
details: true
});
}
// Valid display names
validateDisplayName('John Doe').valid; // true
validateDisplayName('Alice (Admin)').valid; // true
validateDisplayName('Bob 123').valid; // true
Validation Rules
Default Username Requirements
- Minimum length: 3 characters
- Maximum length: 30 characters
- Cannot start with a number
- Cannot contain spaces
- Cannot contain special characters
- Case-insensitive blocking for reserved names
Allowed Characters (Default)
When allowSpecialChars is false (default):
- Letters:
a-z, A-Z
- Numbers:
0-9 (but not at start by default)
- Underscores:
_
- Hyphens:
-
- Dots:
.
Special Characters
When allowSpecialChars is true, these additional characters are allowed:
! @ # $ % ^ & * ( ) , . ? " : { } | < >
Complete Validation Example
import { isUsername } from 'validauth';
class UsernameValidator {
constructor() {
this.blockedUsernames = [
'admin', 'root', 'system', 'api', 'moderator',
'administrator', 'support', 'help', 'info',
'contact', 'sales', 'marketing', 'dev'
];
}
validate(username) {
// Step 1: Basic validation
const result = isUsername(username, {
minLength: 3,
maxLength: 20,
allowSpecialChars: false,
forbidSpaces: true,
forbidStartingNumber: true,
blockedUsernames: this.blockedUsernames,
details: true
});
if (!result.valid) {
return {
available: false,
errors: result.errors
};
}
// Step 2: Additional custom checks
const customErrors = [];
// Check for consecutive special characters
if (/[_.-]{2,}/.test(username)) {
customErrors.push('Username cannot contain consecutive special characters');
}
// Check for profanity (example)
const profanityWords = ['badword1', 'badword2'];
if (profanityWords.some(word => username.toLowerCase().includes(word))) {
customErrors.push('Username contains inappropriate content');
}
if (customErrors.length > 0) {
return {
available: false,
errors: customErrors
};
}
return {
available: true,
username: result.username
};
}
// Check if username already exists in database
async checkAvailability(username) {
const validation = this.validate(username);
if (!validation.available) {
return validation;
}
// Check database (example)
// const exists = await db.users.exists({ username });
// if (exists) {
// return {
// available: false,
// errors: ['Username is already taken']
// };
// }
return {
available: true,
username: validation.username
};
}
}
// Usage
const validator = new UsernameValidator();
const result = validator.validate('john_doe');
if (result.available) {
console.log('Username is valid:', result.username);
} else {
console.error('Invalid username:', result.errors);
}
Error Handling
Always provide clear feedback to users about why their username was rejected. Use the details option to get specific error messages.
import { isUsername } from 'validauth';
function getUsernameFeedback(username) {
const result = isUsername(username, { details: true });
if (result.valid) {
return {
status: 'success',
message: 'Username is valid'
};
}
// Map errors to user-friendly messages
const friendlyMessages = {
'Username must be at least': 'Username is too short',
'Username must be no more than': 'Username is too long',
'Username cannot contain spaces': 'Spaces are not allowed',
'Username cannot contain special characters': 'Only letters, numbers, and _ - . are allowed',
'Username cannot start with a number': 'Username must start with a letter',
'This username is not allowed': 'This username is reserved'
};
const userMessages = result.errors.map(error => {
for (const [key, message] of Object.entries(friendlyMessages)) {
if (error.includes(key)) {
return message;
}
}
return error;
});
return {
status: 'error',
message: userMessages[0],
errors: userMessages
};
}
// Usage
const feedback = getUsernameFeedback('ab!');
console.log(feedback);
/* Returns:
{
status: 'error',
message: 'Username is too short',
errors: [
'Username is too short',
'Only letters, numbers, and _ - . are allowed'
]
}
*/
Best Practices
Recommended Settings
- Keep
minLength at 3 or higher to prevent very short usernames
- Set
maxLength based on your UI constraints (20-30 is typical)
- Enable
forbidSpaces for login usernames
- Use
blockedUsernames to reserve admin and system names
- Validate uniqueness against your database separately
Security Considerations
- Always validate usernames on the server side, not just client side
- Usernames are case-sensitive for display but typically stored lowercase
- Block common admin names to prevent social engineering
- Consider implementing rate limiting on username checks
- Sanitize usernames before displaying to prevent XSS (see XSS validator)
UX Recommendations
- Show real-time validation feedback as users type
- Display available characters and rules clearly
- Suggest alternative usernames if one is taken
- Allow users to preview how their username will appear