|
| 1 | +# Challenge 21: Validate Username |
| 2 | + |
| 3 | +Write a function that checks if a given string is a valid username. A valid username should contain only alphanumeric characters and underscores, and should be between 4 and 16 characters long. |
| 4 | + |
| 5 | +Write a function called `isValidUsername` that takes a string `username` in its parameter and returns true or false. |
| 6 | + |
| 7 | +## Answer |
| 8 | + |
| 9 | +```javascript |
| 10 | +// Function to validate username |
| 11 | +function isValidUsername(username) { |
| 12 | + // Regular expression pattern for username validation |
| 13 | + const regex = /^[a-zA-Z0-9_]{4,16}$/; |
| 14 | + |
| 15 | + // Test if the string matches the username pattern |
| 16 | + return regex.test(username); |
| 17 | +} |
| 18 | +``` |
| 19 | + |
| 20 | +## Answer Explanation |
| 21 | + |
| 22 | +The `isValidUsername` function takes a string as input and uses a regular expression to check if it's a valid username. The regular expression `^[a-zA-Z0-9_]{4,16}$` is used to match the username pattern. |
| 23 | + |
| 24 | +The test method is then used to check if the input string matches the regular expression, if it's a valid username function returns true otherwise false. |
0 commit comments