不是RegEx的大用戶 - 從來沒有真正理解它們!但是,我覺得檢查用戶名字段輸入的最好方法是隻允許字母(上或下),數字和_字符,並且必須按照站點策略以字母開頭。我的RegEx和代碼是這樣的:Javascript RegEx沒有像預期的那樣返回false
var theCheck = /[a-zA-Z]|\d|_$/g;
alert(theCheck.test(theUsername));
儘管嘗試各種組合,一切都返回「真實」。
任何人都可以幫忙嗎?
不是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:現在,它沒有。 –