1

I am trying to make username validation with regex and PHP. The requirements are:

  • No spaces
  • Only lowercase letters and digits
  • No special characters except (.),(-),(_) and the user cannot use two or more special characters together
  • username should not start with special characters
  • minimum length 6 and maximum 25

this is what I've done so far /^[a-z0-9]{6,25}\S*$/

0

1 Answer 1

1

If there can be no special char at the end of the username, use

^(?=.{6,25}$)[a-z0-9]+(?:[._-][a-z0-9]+)*$

Else, if there can be a special char at the end:

^(?=.{6,25}$)[a-z0-9]+(?:[._-][a-z0-9]+)*[._-]?$

See this regex demo.

Details:

  • ^ - start of string
  • (?=.{6,25}$) - 6 to 25 chars other than line break chars allowed in the string
  • [a-z0-9]+ - one or more digits or lowercase letters
  • (?:[._-][a-z0-9]+)* - zero or more occurrences of a ., _ or - followed with one or more digits or lowercase letters
  • [._-]? - an optional ., _ or -
  • $ - end of string.
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for the answer, also I forgot to mention the username should not consist of only numbers how to add this? and where can I learn more about regex codes. thank you.
@Tanuj1899 No numbers only requirement is easy to implement with a negative lookahead: ^(?!\d+$)(?=.{6,25}$)[a-z0-9]+(?:[._-][a-z0-9]+)*$
I do not know your level of regex knowledge :) so that I can only suggest doing all lessons at regexone.com, reading through regular-expressions.info, regex SO tag description (with many other links to great online resources), and the community SO post called What does the regex mean. Also, rexegg.com is worth having a look at.
@Tanuj1899 I also posted some regex articles and am planning to start a Youtube channel with some quick regex demos. I will let you know when I start it.
Thank you for all the resources, I am just getting started with regex. Your channel will be very helpful for me and all others seeking help.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.