简体   繁体   中英

Validate password - must contain 2 capital letters

Can someone tell me why this function doesn't work? the password length and the check of number work perfectly. But it is something wrong with the check of big capitals...

function validera() {
var passw = document.getElementById("User-Password").value;
var upper = /[A-Z]/ ;
var number = /[0-9]/;

if (passw.length < 6 || !number.test(passw) || !upper.test(passw)) {
    if (passw.length < 6) {
        alert("Please make sure password is longer than 6 characters.")
        return false;
    }

    var counter = 0;
    var i;
    for(i = 0; i < passw.length; i++){
       passw.charAt(i)
       if(upper.test(passw.charAt(i))){
           counter++;
           break;
       }
   }

    if( counter < 2 ){
        alert("Please make sure password includes 2 capital letters")
        return false;

    }

    if (!number.test(passw)) {
        alert("Please make sure Password Includes a Digit")
        return false;
    }

} else {
    alert("Account created")
}

Or do I have to use regex?

If you are planning to use regex to find two capital letters then you can use like

\w*[A-Z]\w*[A-Z]\w*

Test this here on regextester

Here Check it out Fiddle

CreateRandomPassword(Length, isUpperAlpha, isLowerAlpha, isNumaric ,SpecialChars)

I have developed easy function to generate password

Here's a function that returns an object with a message and a boolean.

Example snippet:

 function testPassword(pwd) { if (pwd.length <= 6) return { valid: false, message: "Please make sure password is longer than 6 characters." }; if(!/[AZ].*[AZ]/.test(pwd)) return { valid: false, message: "Please make sure password includes 2 capital letters" }; if (!/\\d/.test(pwd)) return { valid: false, message: "Please make sure Password Includes a Digit" }; if (/\\s/.test(pwd)) return { valid: false, message: "Please only use visible characters" }; return { valid: true, message: "Valid Password" }; } console.log(testPassword('Val1dPassword')); console.log(testPassword('SH0rt')); console.log(testPassword('No2capitals')); console.log(testPassword('NoDigits')); console.log(testPassword('Has\\tat least 1 WhiteSpace'));

Then your function can be simplified.

function validera() {
    let passw = document.getElementById("User-Password").value;
    let check = testPassword(passwd);
    if (check.valid) {
        alert(check.message);
        return false;
    }
     else {
        alert("Account created")
    }
  }

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