Reputation: 5442
I want that the usernames be 4-32 chars long.
function validate_username($input)
{
return (bool) preg_match('/^([a-z]+[a-z0-9_]*){4,32}$/i', $input);
}
What is wrong with my try, please?
var_dump(validate_username('h_q8Y'));
which returns FALSE
But var_dump(validate_username('h_q8Yewre_'));
returns TRUE
Upvotes: 2
Views: 77
Reputation: 57690
Your regular expression is wrong. Here
([a-z]+[a-z0-9_]*)
matches h_q8Y
. {4,32}
means there will be at least 4 or at most 32 of h_q8Y
. But you provided only one h_q8Y
. Hence its not working.
Its better you use following expression.
/^[a-z]\w{3,31}$/i
Upvotes: 2
Reputation: 145512
{4,32}
repeats the inner paranthesis match 4 times. You need at least 4 letters to satisfy it.
To assert the length you need a lookahead assertion which is independent from the character class specifier:
preg_match('/^(?=.{4,32})([a-z]+[a-z0-9_]*)$/i'
| |
asserts length |
checks char mix
Upvotes: 5
Reputation: 44289
You are repeating your repetition 4 to 32 times. I assume that you wanted to make sure that the username starts with a letter. In this case, this is probably what you are looking for:
preg_match('/^[a-z]\w{3,31}$/i', $input);
Note that \w
is equivalent to [a-zA-Z0-9_]
.
Upvotes: 3