1

不是 RegEx 的大用户——从来没有真正理解过它们!但是,我认为检查用户名字段输入的最佳方法是使用仅允许字母(大写或小写)、数字和 _ 字符的输入,并且必须根据站点政策以字母开头。My RegEx 和代码是这样的:

var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));

尽管尝试了各种组合,但一切都返回“真实”。

任何人都可以帮忙吗?

4

3 回答 3

3

您的正则表达式是说“确实theUsername包含字母、数字或以下划线结尾”。

试试这个:

var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"

这表示“theUsername以字母开头,仅包含字母、数字或下划线”。

注意:我认为这里不需要“g”,这意味着“所有匹配项”。我们只想测试整个字符串。

于 2012-05-14T22:56:42.443 回答
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
于 2012-05-14T22:57:17.290 回答
1

使用它作为你的正则表达式:

^[A-Za-z][a-zA-Z0-9_]*$
于 2012-05-14T22:56:13.330 回答