This one worked for me: /(^\D{2,}$)|(^\D+\d{2,}$)/
The breakdown for me was:
If it must start with a letter, then I should use ^\D.
Since I know that the minimum length is 2 and that requires 2 letters, then the first thing I need to check for is ^\D{2,} at a minimum.
In all other cases, I know that the username must start with a letter and, if it has a number, it needs to end with the number. In this case, I figured that ^\D+\d{2,}$ would be the best option.
Since these are two different scenarios for the username, and I didn’t want to have one that was super long, I used the | to say that it could be either.
Not sure if this will work for all scenarios, but it worked for this one.
let username = "JackOfAllTrades";
const userCheck = /^[a-z]([0-9]{2,}|[a-z]+\d*)$/i;
let result = userCheck.test(username);
Code Explanation
^ - start of input
[a-z] - first character is a letter
[0-9]{2,0} - ends with two or more numbers
| - or
[a-z]+ - has one or more letters next
\d* - and ends with zero or more numbers
$ - end of input
i - ignore case of input
Hi, need an explanation on why the suggested solution matches the string “JACK” although we specified (no. 6 - and ends with zero or more numbers) it to end with a number? Also, where does the check for the numbers, in the strings, “BadUs3rnam3” and “c57bT3”, that are not in the end, happens? Thanks in advance.
Hi there,
Please allow me to share with you the solution I made for this exercise, based on the given premise or rules. To test for the validity of any username data entry, my solution is, as follows:
/*You may try feeding the sample usernames from the exercise to test the code;
it shall suffice to demonstrate the code works for any username entry, based on the given premise.