I am trying to validate a username in PHP using regex and everything I submit fails the check. I'm super new at this still.
if ( !preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5-31}$/', $joinUser) )
Rules:
I've been working with this online tester and this one too. I read this thread and this thread but wasn't able to understand much as they seems to be a little bit more complicated than mine (lookaheads? and various special characters).
After reading the first thread I linked to, it seems like I'm one of the people that doesn't quite understand how saying "letters" impacts what's thought of as acceptable, i.e. foreign characters, accented characters, etc. I'm really just looking at the English alphabet (is this ASCII?) and numbers 0-9.
Thanks.
Use the filter_var() function to validate whether a string is URL or not: var_dump(filter_var('example.com', FILTER_VALIDATE_URL));
The preg_match() function returns whether a match was found in a string.
The only problem is, you misspelled the last quantifier.
{5-31}
has to be {5,31}
so your regex would be
if ( !preg_match('/^[A-Za-z][A-Za-z0-9]{5,31}$/', $joinUser) )
and you can skip the {1}
, but it does not hurt.
Apparently all you needed to change was 5,31 from 5-31.
Working example:
if (preg_match('/^[A-Za-z]{1}[A-Za-z0-9]{5,31}$/', "moo123"))
{
echo 'succeeded';
}
else
{
echo 'failed';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With