[英]Javascript password validation with regular expression
我嘗試使用以下條件驗證密碼字段,如果滿足要求,密碼字段應將其顏色更改為綠色,否則應為紅色: 一個小寫字符 一個大寫字符 一個數字 一個特殊字符 最少 8 個字符我嘗試過正則表達式,但不知何故,即使我輸入了具有所有要求的密碼,它也只會使它變紅。 任何的想法?
let passwordField = document.getElementById("password");
passwordField.addEventListener("focusout", () => {
let checkPass =
/^(?=.*[a-z])(?=.*[A-Z])(?=.*d)(?=.*[@$!%*?&])[A-Za-zd@$!%*?&]{8,}$/;
if (checkPass.test(password.value)) {
passwordField.style.backgroundColor = "green";
console.log("green");
} else {
passwordField.style.backgroundColor = "red";
console.log("red");
}
});
正則表達式應該是:
^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})
在哪里:
(?=.*[az])
(?=.*[AZ])
(?=.*[0-9])
(?=.*[!@#\\$%\\^&\\*])
(?=.{8,})
let passwordField = document.getElementById("password"); passwordField.addEventListener("focusout", () => { let checkPass = new RegExp("^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.*[!@#\\$%\\^&\\*])(?=.{8,})"); if (checkPass.test(password.value)) { passwordField.style.backgroundColor = "green"; console.log("green"); } else { passwordField.style.backgroundColor = "red"; console.log("red"); } });
<input id="password" />
結果是:
請檢查這個,它和你想要的完全一樣
let passwordField = document.getElementById("password"); passwordField.addEventListener("focusout", () => { var decimal= /^(?=.*\\d)(?=.*[!@#$%^&*])(?=.*[az])(?=.*[AZ]).{8,}$/; if (passwordField.value.match(decimal)) { passwordField.style.backgroundColor = "green"; console.log("green"); } else { passwordField.style.backgroundColor = "red"; console.log("red"); } });
<!DOCTYPE html> <html lang="en"> <head> <title>Password</title> </head> <body> <h1>This is a password validation</h1> <input id="password" /> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.