lets-validate-username 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +33 -0
- package/package.json +12 -0
- package/test.js +12 -0
package/index.js
ADDED
@@ -0,0 +1,33 @@
|
|
1
|
+
function validateUsername(username, existingUsernames) {
|
2
|
+
const errors = [];
|
3
|
+
|
4
|
+
// Rule 1: Length between 3 and 15 characters
|
5
|
+
if (username.length < 3 || username.length > 15) {
|
6
|
+
errors.push("Username must be between 3 and 15 characters.");
|
7
|
+
}
|
8
|
+
|
9
|
+
// Rule 2: Only letters, numbers, and underscores
|
10
|
+
if (!/^[a-zA-Z0-9_]+$/.test(username)) {
|
11
|
+
errors.push("Username can only contain letters, numbers, and underscores.");
|
12
|
+
}
|
13
|
+
|
14
|
+
// Rule 3: Username must be unique
|
15
|
+
if (existingUsernames.includes(username)) {
|
16
|
+
errors.push("Username is already taken.");
|
17
|
+
}
|
18
|
+
|
19
|
+
// Return validation result
|
20
|
+
if (errors.length > 0) {
|
21
|
+
return {
|
22
|
+
valid: false,
|
23
|
+
errors: errors,
|
24
|
+
};
|
25
|
+
}
|
26
|
+
|
27
|
+
return {
|
28
|
+
valid: true,
|
29
|
+
message: "Username is valid!",
|
30
|
+
};
|
31
|
+
}
|
32
|
+
|
33
|
+
module.exports = validateUsername;
|
package/package.json
ADDED
@@ -0,0 +1,12 @@
|
|
1
|
+
{
|
2
|
+
"name": "lets-validate-username",
|
3
|
+
"version": "1.0.0",
|
4
|
+
"description": "A simple npm package to validate usernames based on length, allowed characters, and uniqueness.",
|
5
|
+
"main": "index.js",
|
6
|
+
"scripts": {
|
7
|
+
"test": "node test.js"
|
8
|
+
},
|
9
|
+
"keywords": ["username", "validator", "npm-package", "validation"],
|
10
|
+
"author": "Zoha",
|
11
|
+
"license": "MIT"
|
12
|
+
}
|
package/test.js
ADDED
@@ -0,0 +1,12 @@
|
|
1
|
+
const validateUsername = require('./index');
|
2
|
+
|
3
|
+
// Example usernames
|
4
|
+
const existingUsernames = ["john_doe", "jane123", "cool_guy"];
|
5
|
+
|
6
|
+
// Test cases
|
7
|
+
console.log(validateUsername("john_doe", existingUsernames)); // Invalid: already taken
|
8
|
+
console.log(validateUsername("new_user", existingUsernames)); // Valid
|
9
|
+
console.log(validateUsername("ab", existingUsernames)); // Invalid: too short
|
10
|
+
console.log(validateUsername("this_is_a_really_long_username", existingUsernames)); // Invalid: too long
|
11
|
+
console.log(validateUsername("user@name!", existingUsernames)); // Invalid: bad characters
|
12
|
+
|