php - Username may contain lowercase characters and numbers

I want to allow lowercase characters and numbers in username field.
But with following conditions...
- Only numbers as username NOT allowed (e.g. only mobile number)
- Only lowercase characters allowed (e.g. without any number in username)
- Lowercase characters + numbers allowed (e.g. combination of lowercase and numbers)
- Minimum length 8 characters required
- Maximum length 20 characters allowed
What php regex will do it ?
I tried with following, but it forces lowercase + numbers. Only lowercase username not allowing.
$username_pattern = '/^(?=.*[a-z])(?=.*[a-z])(?=.*\d)[a-z0-9]{8,20}$/';
I want only lowercase and/or lowercase+numbers ( min 8 and max 20 ) in username
Help appreciated.
Answer
Solution:
You can simplify it to not allowing only digits
^(?!\d*$)[a-z0-9]{8,20}$
Explanation
^
Start of string(?!\d*$)
Negative lookahead, assert not only digits till end of string[a-z0-9]{8,20}
Match 8-20 times a char a-z or a digit 0-9$
End of string
$username_pattern = '/^(?!\d*$)[a-z0-9]{8,20}$/';
$userNames = [
"1a3b5678",
"1a3b5678abcd",
"12345678",
"1a3b5678abcddddddddddddddddddddddddddddddd",
"1a3B5678",
"a1"
];
foreach ($userNames as $userName) {
if (preg_match($username_pattern, $userName)) {
echo "Match - $userName" . PHP_EOL;
} else {
echo "No match - $userName" . PHP_EOL;
}
}
Output
Match - 1a3b5678
Match - 1a3b5678abcd
No match - 12345678
No match - 1a3b5678abcddddddddddddddddddddddddddddddd
No match - 1a3B5678
No match - a1
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: a non-numeric value encountered in
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.