Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PHP regex to validate username

Tags:

regex

php

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.

like image 621
soycharliente Avatar asked Nov 15 '12 07:11

soycharliente


People also ask

How validate URL in PHP regex?

Use the filter_var() function to validate whether a string is URL or not: var_dump(filter_var('example.com', FILTER_VALIDATE_URL));

What is the use of Preg_match in PHP?

The preg_match() function returns whether a match was found in a string.


2 Answers

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.

like image 187
stema Avatar answered Sep 20 '22 17:09

stema


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';
}
like image 35
Andrius Naruševičius Avatar answered Sep 17 '22 17:09

Andrius Naruševičius