Const
// Valid usernames
const validUsernames = [
'user123',
'language_learner',
'student-2024',
'TeacherMaria',
'quiz_master_pro'
];
validUsernames.forEach(username => {
const result = UsernameSchema.parse(username);
console.log(`${username} is valid`);
});
// Username availability check
router.get('/username/check/:username', validate({
params: z.object({ username: UsernameSchema })
}), async (req, res) => {
const { username } = req.params; // Validated username
const isAvailable = await userService.isUsernameAvailable(username);
res.json({ username, available: isAvailable });
});
// Profile update with username validation
const ProfileUpdateSchema = z.object({
username: UsernameSchema.optional(),
displayName: z.string().max(100).optional(),
bio: z.string().max(500).optional()
});
// Error handling for invalid usernames
try {
UsernameSchema.parse('ab'); // Too short
} catch (error) {
// Throws: "Username must be at least 3 characters"
}
try {
UsernameSchema.parse('user@name'); // Invalid character
} catch (error) {
// Throws: "Username can only contain letters, numbers, underscores, and hyphens"
}
Username validation schema with character restrictions and length limits
Comprehensive username validation schema that enforces consistent username format requirements across the application. The schema ensures usernames are appropriate length, contain only safe characters, and follow patterns that support user identification while preventing security vulnerabilities and user experience issues.
The character restrictions allow letters, numbers, underscores, and hyphens, which provides flexibility for user expression while preventing problematic characters that could cause issues in URLs, database queries, or user interfaces. The length limits ensure usernames are meaningful while preventing abuse through excessively long identifiers.
Security considerations include prevention of username injection attacks through character restrictions, elimination of special characters that could cause parsing errors in various contexts, and consistent format that supports username-based authentication and user lookup operations. The schema maintains compatibility with URL encoding and various user interface components.