A regular expression for using an email address as username?

ぐ巨炮叔叔 提交于 2019-12-13 05:17:49

问题


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?


回答1:


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

References

  • How to Find or Validate an Email Address?


来源:https://stackoverflow.com/questions/22815707/a-regular-expression-for-using-an-email-address-as-username

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!