admin 管理员组文章数量: 1086019
I'm trying to validate a username field in my form via client-side valdiation and I'm having some trouble.
I'm trying to use match them against regexs, which seems to work for my password strength/match. However when I try and change the regular expression to one that is suitable for usernames it doesn't work.
This is the regular expression that works, it checks to see if the length is at least 6 chars long.
var okRegex = new RegExp("(?=.{6,}).*", "g");
This is the other regular expression which does not work:
var okRegex = new RegExp("/^[a-z0-9_-]{3,16}$/");
How do I write a regex that performs username validation? (That it's of a certain length, has only letters and numbers)
I'm trying to validate a username field in my form via client-side valdiation and I'm having some trouble.
I'm trying to use match them against regexs, which seems to work for my password strength/match. However when I try and change the regular expression to one that is suitable for usernames it doesn't work.
This is the regular expression that works, it checks to see if the length is at least 6 chars long.
var okRegex = new RegExp("(?=.{6,}).*", "g");
This is the other regular expression which does not work:
var okRegex = new RegExp("/^[a-z0-9_-]{3,16}$/");
How do I write a regex that performs username validation? (That it's of a certain length, has only letters and numbers)
Share Improve this question edited Jan 17, 2014 at 15:02 George Stocker 57.9k29 gold badges181 silver badges238 bronze badges asked Jan 17, 2014 at 14:54 user3112518user3112518 372 silver badges6 bronze badges 3- 1 What are the rules for usernames that you are trying to enforce? – rusmus Commented Jan 17, 2014 at 14:57
- good helping tool for regexps: regex101./r/bB5aL3 – caramba Commented Jan 17, 2014 at 15:04
-
if(/^[a-z0-9_-]{3,16}$/.test(userNameVar)) {//username is good!}
– Obversity Commented Jan 17, 2014 at 15:05
2 Answers
Reset to default 7You're mixing regex literals with the RegExp
constructor. Use one or the other, but not both:
okRegex = new RegExp('^[a-z0-9_-]{3,16}$');
or
okRegex = /^[a-z0-9_-]{3,16}$/;
As @zzzzBow answered you are mixing up two ways of using regular expressions. Choose one or the other. Now, a break down:
^
Matches the beginning of the string (that means that the string must start with whatever follows).
[a-z0-9_-]
Matches the charecters a-z, A-Z, digits 0-9 _ (underscore) and - (dash/hyphen).
{3,16}
States that there must be 3-16 occurences from the above character class.
$
Matches the end of the string, so the can't be anything after the 16 characters above.
Hope that helps.
本文标签:
版权声明:本文标题:javascript - regex that checks that a string is between two lengths and has only letters and numbers - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744001354a2516501.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论