Question

Is there a regular expression out there for using a normal username OR an email address as a username? I would like a user to be able to enter their own username, or just use their email address as the username and I am unable to find any reliable information on how to achieve this properly. It would still have to pass validation as well, for example: if the user chooses to make their own username, it would have to abide by my policy for usernames, which limits them to starting with a letter or number, and no special characters, or if they enter an email, it would have to abide by the email rules(typical email rules). Anyone have a suggestion for this?

Was it helpful?

Solution

Try this regular expression:

/^(?:[A-Z\d][A-Z\d_-]{5,10}|[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4})$/i

The expression has two parts:

  • The first part validates a username. Feel free to optimize this part for matching you own policy. The regex here accepts username starting with a letter or a number. A username can't belonger than 11 characters. - and '_' are allowed.

  • The second part validates an email. This regex validates 99% of emails in use as of this writing. However, you may use another email regex.

Description

Regular expression visualization

References

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top