Javascript RegEx没有像预期的那样返回false
不是RegEx的大用户 - 从来没有真正理解它们!但是,我觉得检查用户名字段输入的最好方法是只允许字母(上或下),数字和_字符,并且必须按照站点策略以字母开头。我的RegEx和代码是这样的:Javascript RegEx没有像预期的那样返回false
var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));
尽管尝试各种组合,一切都返回“真实”。
任何人都可以帮忙吗?
你的正则表达式时说:“确实theUsername
包含字母,数字或下划线结束”。
试试这个:
var theCheck = /^[a-z]([a-z_\d]*)$/i; // the "i" is "ignore case"
这是说“theUsername
以字母开头且只包含字母,数字或下划线”。
注:我不认为你需要在这里的“克”,这意味着“所有比赛”。我们只是想测试整个字符串。
使用此为您的正则表达式:
^[A-Za-z][a-zA-Z0-9_]*$
怎么是这样的:
^([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
第二块的长度过大。一个'+'应该做的(我们不知道应该多久) – Alfabravo
@Alfabravo我实际上是要添加一些解释。但是,我希望它至少有两个以上的字符 –
奖金,OP应搜索常见的正则表达式模式。很确定其他人已经通过这种痛苦 – Alfabravo
这是否强制第一个字符是一个字母? – tip2tail
@ tip2tail:现在,它没有。 –