Search code examples
phpregexpcre

How to validate username with regular expression


I want to check username validation before signup, but it is a little bit complex, I tried too many variation but I could not.

  • Username min and max length is 6 and 20
  • Username can contain a-z A-Z 0-9 and ç Ç
  • Username can contain underscore but can not contain start and end of username
  • Username can not contain more then one underscore
  • Username can contain numbers but can not contain more than 3 numbers , number order is not important

For example;

VALID:

username
username1
username23
username456
7username
89username
123username
user_name
user_name1
1user_name2
123user_name
1u2s3er
4u5s6er

INVALID:

_username <-- start with underscore
username_ <-- end with underscore
_username_ <-- contains underscore more than 1, start and end with underscore
user__name <-- contains underscore more than 1
user_na_me <-- contains underscore more than 1
username1000 <-- contains number more than 3
user01name23 <-- contains number more than 3
1u2s3e4r <-- contains number more than 3

This regex rule is good for my first three conditions but I need add limit for numbers and underscores.

^(?=.{6,20}$)(?![_])[a-zA-Z0-9çÇ_]+(?<![_])$

Thanks.


Solution

  • I SOLVED, THANKS.

    THE SOLUTION;

    ^(?!(.*[_].*){2,}$)(?!(.*[0-9].*){4,}$)(?=.{6,20}$)(?![_])[a-zA-Z0-9çÇ_]+(?<![_])$