最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript username validation - Stack Overflow

programmeradmin1浏览0评论

What would be a good regex to use for validating a username, forbidding all special chars except the "@" symbol in case people want to use their email address as their username?

What would be a good regex to use for validating a username, forbidding all special chars except the "@" symbol in case people want to use their email address as their username?

Share Improve this question asked Feb 15, 2011 at 0:55 user460114user460114 1,8954 gold badges31 silver badges56 bronze badges 1
  • 3 Just a reminder, you should also validate on the server-side, because a malicious user could bypass your Javascript validation. – muddybruin Commented Feb 15, 2011 at 1:02
Add a ment  | 

2 Answers 2

Reset to default 2
^([a-zA-Z0-9.]+@){0,1}([a-zA-Z0-9.])+$

This will permit A-Z, a-z, 0-9 and ., and at most one @

Well I guess this may work for your circumstances (see below)...

var userRegex = /^[\w\.@]{6,100}$/;

This will match...

  • word characters such as 0-9, A-Z, a-z, _
  • literal period
  • literal @
  • between 6 and 100 characters long

You should probably look at the Email RFC, which states, amongst other characters, that the following are legal: ! # $ % & ' * + - / = ? ^ _ `` { | } ~. This means that the regex above will not allow all emails.

So...

var validUsername = document.getElementById('username').value.match(userRegex);
发布评论

评论列表(0)

  1. 暂无评论