在 Javascript 中,我嘗試添加這樣的函式來檢查輸入的密碼是否包含任何符號(特殊)字符,例如!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?.
所以我這樣做了:
function checkpasswordlength(){
var format1 = /^[!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?]*$/;
var e = document.getElementById("password").value;
if(e != "") {
if(e.length >= 12){
if(e.match(format1)){
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "strong";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
}else{
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "normal";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', '#3cb878', 'important');
}
}else{
document.getElementById("passwordstrengthstatus").style.display = "inline";
document.getElementById("passwordstrengthstatus").innerHTML = "weak";
document.getElementById("passwordstrengthstatus").style.setProperty('background-color', 'red', 'important');
}
}else{
document.getElementById("passwordstrengthstatus").style.display = "none";
}
}
如您所見,它將檢查密碼是否為空且長度是否超過12字符,然后繼續檢查e.match(format1).
但問題是,當我也輸入這些字符時,它不會將此條件回傳為真,因此該訊息strong不會出現并且仍然normal在螢屏上顯示訊息。
那么這有什么問題呢?
如何解決此問題并正確檢查字串是否包含書寫符號?
uj5u.com熱心網友回復:
如果您只想檢查是否存在至少一個符號字符,則洗掉^and$錨點并使用:
var format1 = /[!@#$%^&*()_ \=\[\]{};':"\\|,.<>\/?-]/;
請注意,連字符已移至字符類的末尾。如果您想堅持使用原始模式并匹配整個密碼,請修改為:
var format1 = /^.*[!@#$%^&*()_ \=\[\]{};':"\\|,.<>\/?-].*$/;
uj5u.com熱心網友回復:
僅當密碼僅包含特殊字符時,您當前的正則運算式才匹配。嘗試在里面添加 a-zA-Z0-9
^[a-zA-Z0-9!@#$%^&*()_ \-=\[\]{};':"\\|,.<>\/?]*$
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/533020.html
