用户名的 JavaScript 正则表达式没有空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15933727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JavaScript Regular Expression For Usernames No Spaces
提问by jon333
I am seeking help with a JavaScript RegEx for user names. Basically I need the letters A-Z, digits, periods, dashes, underscores, dollar signs, at signs, the asterisk, and the exclamation point to be allowed and the username can be up to 30 characters long. No spaces or commas should be allowed for example.
我正在寻求有关用户名的 JavaScript RegEx 的帮助。基本上我需要允许使用字母 AZ、数字、句点、破折号、下划线、美元符号、at 符号、星号和感叹号,并且用户名最长可达 30 个字符。例如,不应允许使用空格或逗号。
Allowed characters:
允许的字符:
[a-zA-Z0-9]
.
-
_
$
@
*
!
- User.name = passes
- User name = fails
- User,name = fails
- usernameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = fails
- 用户名 = 通行证
- 用户名 = 失败
- 用户,名称 = 失败
- usernameeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee = 失败
回答by Andrew Clark
The following should work:
以下应该工作:
/^[a-zA-Z0-9.\-_$@*!]{3,30}$/
Note that I also enforced a minimum length of 3 characters, change this to whatever you actually want.
请注意,我还强制要求最小长度为 3 个字符,请将其更改为您真正想要的任何内容。
JSFiddle: http://jsfiddle.net/5F5cQ/1/
JSFiddle:http: //jsfiddle.net/5F5cQ/1/
回答by Walls
You can use ^[-\w\.\$@\*\!]{1,30}$
, where 1
and 30
are the bounds that you can change depending on how short the password needs to be at a minimum.
您可以使用^[-\w\.\$@\*\!]{1,30}$
, where1
和30
是您可以更改的边界,具体取决于密码最少需要多短。
\w
provides the Numbers, letters, and underscore coverage, followed by all the special chars you are allowing. Make sure to properly escape the special chars since a lot of them are used in actual regex parsing.
\w
提供数字、字母和下划线覆盖,然后是您允许的所有特殊字符。确保正确转义特殊字符,因为它们中有很多用于实际的正则表达式解析。
Using your examples provided (and some extra ones) you can see the regex working here.
使用您提供的示例(以及一些额外的示例),您可以看到正则表达式在此处工作。