Dr.Seuss
Dr.Seuss

Reputation: 49

Regex to check if username is valid or not

Good morning,

I want to check if the usernames the users are picking are valid or not. Sadly I can't find any Regex which suits my needs and writing it myself doesn't bring me far. I hope I can get some help here. :)

Rules:
3-26 Digits
a-z
A-Z
0-9
One dot allowed ( . )

Until now I have:

if ( !preg_match('/^[A-Za-z][A-Za-z0-9]{3,26}$/', $joinUser) ) 

But the dot is making me problems.

Thanks for any help!

Upvotes: 2

Views: 517

Answers (2)

kamal pal
kamal pal

Reputation: 4207

Check it out! it would match for single period or underscore, not multiple, not both. hope this helps!

if(preg_match('/^(?=.{3,26}$)[a-z0-9]+(?:[._][a-z0-9]+)?$/i', $username)) 
    echo 'Match';
echo 'Not Match';

Upvotes: 0

Jota
Jota

Reputation: 17611

Try this approach with a negative lookahead:

'/^(?!.*[.].*[.])[A-Za-z0-9.]{3,26}$/'

or

'/^(?!.*\..*\.)[A-Za-z0-9.]{3,26}$/' 

using escapes instead of character classes.

The negative lookahead will cause this regex not to match something with two or more periods.

Upvotes: 2

Related Questions