不是RegEx的大用户 - 从未真正了解它们!但是,我觉得检查用户名字段输入的最佳方法是使用只允许字母(上部或下部),数字和_字符的输入,并且必须根据网站策略以字母开头。 My RegEx和代码是这样的:
var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));
尽管尝试了各种组合,但一切都回归“真实”。
有人可以帮忙吗?
答案 0 :(得分:3)
你的正则表达式是说“theUsername
包含字母,数字或以下划线结尾”。
请改为尝试:
var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"
这表示“theUsername
以字母开头,只包含字母,数字或下划线”。
注意:我认为你不需要“g”,这意味着“所有匹配”。我们只想测试整个字符串。
答案 1 :(得分:3)
这样的事情怎么样:
^([a-zA-Z][a-zA-Z0-9_]{3,})$
解释整个模式:
^ = Makes sure that the first pattern in brackets is at the beginning
() = puts the entire pattern in a group in case you need to pull it out and not just validate
a-zA-Z0-9_ = matches your character allowances
$ = Makes sure that this must be the entire line
{3,} = Makes sure there are a minimum of 3 characters.
You can add a number after the comma for a character limit max
You could also use a +, which would merely enforce at least one character match the second pattern. A * would not enforce any lengths
答案 2 :(得分:1)
将此作为你的正则表达式:
^[A-Za-z][a-zA-Z0-9_]*$