15

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:

  • Must start with letter
  • 6-32 characters
  • Letters and numbers only

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.

Community
  • 1
  • 1
soycharliente
  • 777
  • 2
  • 7
  • 26

4 Answers4

36

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.

stema
  • 90,351
  • 20
  • 107
  • 135
4

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';
}
Andrius Naruševičius
  • 8,348
  • 7
  • 49
  • 78
2

Try this:

if ( !preg_match('/^[A-Za-z][A-Za-z0-9]{5,31}$/', $joinUser) )
rajasaur
  • 5,340
  • 2
  • 27
  • 22
  • 1
    "Try this" answers are low value on Stackoverflow because they do very little to educate/empower thousands of future researchers. – mickmackusa May 31 '19 at 13:57
0

another answer :

if (strlen($username) >= 5 && strlen($username) <= 31 && 
ctype_alnum($username)){

     echo "valid username";
                
}else{

     echo "invalid username";

}
Joukhar
  • 724
  • 1
  • 3
  • 18