简体   繁体   中英

Password validation is not working in the login form

Password validation is not working in the login form. Here is my code:

function verifyPassword() {
  var str = document.getElementById("t1").value;
  if (str.match(/[a-z]/g) &&
    str.match(/[A-Z]/g) &&
    str.match(/[0-9]/g) &&
    str.match(/[^a-zA-Z\d]/g) &&
    str.length >= 8)
    return true;
  else
    return false;
}

You should call the function in the password field's change event and/or the form's submit event, not the form's click event. And you need to test the return value and do something.

document.getElementById('t1').addEventListener('change', function() {
    if (!verifyPassword()) {
        alert("Invalid password");
    }
}
document.getElementByTagName('form')[0].addEventListener('change', function(event) {
    if (!verifyPassword()) {
        event.preventDefault();
        alert("Invalid password");
    }
}

Below you have a cleaner code and is checking your password, you must have: lowercase, uppercase character, and a number. The ^ symbol means that the password must be in this order: lowercase, uppercase, number and must be more than 8 characters.

The syntax ?=.*[x] means that you must have the condition x in your string.

Your old code was only checking if your string has any of these (lowercase, uppercase characters, numbers) but didn't put the condition that you must have all of these and for your password system this was useless.

 function verifyPassword() { var str = document.getElementById("t1").value; var regEx = new RegExp("^(?=.*[az])(?=.*[AZ])(?=.*[0-9])(?=.{8,})"); if (regEx.test(str) && str.length >= 8) console.log("good") else console.log("bad") }
 <div class="txt_field"> <input type="password" id="t1" value="" required> <label>Password</label> <button onclick="verifyPassword()">Verify</button> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM