2017-04-17 76 views
0

我使用JavaScript進行密碼驗證腳麻:驗證與@字符

$.validator.addMethod('mypassword', function(value, element) { 
    return this.optional(element) || (value.match(/^(?=.*\d)(?=.*[A-Z])[0-9a-zA-Z]{8,}$/)); 
}, 
'Password must contain at least one numeric and one uppercase alphabetic character.'); 

我需要的密碼至少爲一個數字,一個大寫字母。但是,如果我在密碼中輸入了諸如@, # ,$這樣的字符,其中包含一個數字和一個大寫阿爾法字符,它仍會顯示錯誤消息。

Password9 accepted 
[email protected] not accepted 

回答

1

這部分在你的正則表達式不允許@

[0-9a-zA-Z] 

如果你不希望任何限制,然後更改[0-9a-zA-Z]{8,}.{8,}

1

根據您的正則表達式,您的密碼必須包含至少8個字母數字字符,而不是其他字符。您的第二個密碼與此條件不符。嘗試

/^(?=.*\d)(?=.*[A-Z]).{8,}$/ 

但我不知道這是你想要的,你可能想限制,以避免,例如設定允許的字符非英文字母,如äöü。

您可能要列出所有允許的字符,像這樣

/^(?=.*\d)(?=.*[A-Z])[0-9a-zA-Z\%\&\/\$\@\#]{8,}$/ 

或者嘗試指定的unicode範圍:

Javascript + Unicode regexes

1

(function(){ 
 
     var regex=/^(?=.*\d)(?=.*[A-Z])[!-~]{8,}$/; \t  
 
\t var arr=["Password9","[email protected]","[email protected]"]; 
 
\t for(var i=0;i<arr.length;i++){ 
 
\t \t console.info(arr[i]+"\t"+(regex.test(arr[i])?"accepted":"not accepted")); 
 
\t } 
 
    })();

試試吧