簡體   English   中英

使用正則表達式驗證 Javascript 密碼

[英]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,})

在哪里:

  1. 較低的字符 = (?=.*[az])
  2. 上字符 = (?=.*[AZ])
  3. 1 個數字 = (?=.*[0-9])
  4. 特殊字符 = (?=.*[!@#\\$%\\^&\\*])
  5. 最小長度為 8 = (?=.{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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM