lets-validate-username
v1.0.1
Published
A simple npm package to validate usernames based on length, allowed characters, and uniqueness.
Downloads
129
Maintainers
Readme
Username Validator Tool
A lightweight and easy-to-use npm package to validate usernames based on configurable rules. This tool checks for length, allowed characters, and uniqueness, making it perfect for user registration systems.
Features
- ✅ Validate username length (default: 3-15 characters).
- ✅ Ensure usernames contain only letters, numbers, and underscores (
_
). - ✅ Check if a username is already taken.
- ✅ Detailed validation messages for better user feedback.
Installation
Install the package via npm:
npm install username-validator-tool
API
validateUsername(username, existingUsernames)
Parameters:
username
(string): The username to validate.existingUsernames
(array): List of existing usernames to check for uniqueness.
Returns: An object with the following structure:
valid: Boolean, // true if valid, false if invalid
message: String, // Success message (if valid)
errors: Array // List of error messages (if invalid)
Examples
1. Valid Username
validateUsername('valid_user', ['john_doe', 'jane123']);
// Output:
// { valid: true, message: 'Username is valid!' }
2. Username too Short
Output:
// { valid: false, errors: ['Username must be between 3 and 15 characters.'] }
3. Invalid Characters
// Output:
// { valid: false, errors: ['Username can only contain letters, numbers, and underscores.'] }
4. Username Already Taken
validateUsername('john_doe', ['john_doe', 'jane123']);
// Output:
// { valid: false, errors: ['Username is already taken.'] }