Reputation: 13
I want to allow lowercase characters and numbers in username field.
But with following conditions...
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.
Upvotes: 0
Views: 3390
Reputation: 163457
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
Upvotes: 1