2
  • The password must be eight characters or longer
  • The password must contain at least 2 lowercase alphabetical character.
  • The password must contain at least 2 uppercase alphabetical character.
  • The password must contain at least 2 numeric character.
  • The password must contain at least 2 special character.

My code

function checkPass(pw) {
var regx = new RegExp("^(?=.*[a-z]{2})(?=.*[A-Z]{2})(?=.*[0-9]{2})(?=.*[!@#\$%\^&\*\)\(]{2})(?=.{8,})");
return regx.test(pw);

}

checkPass('PAssword12#$') => true
checkPass('PaSsword12#$') => false

I want to funtion return true when 2 uppercase character is not sequential.

Thanks!

2 Answers 2

1

You need to use the $ anchor to check for length (and best is to move that check out from lookaheads) and to allow some non-uppercase letters in between like this:

function checkPass(pw) {
  var regx = /^(?=(?:[^a-z]*[a-z]){2})(?=(?:[^A-Z]*[A-Z]){2})(?=(?:\D*\d){2})(?=(?:[^!@#$%^&*)(]*[!@#$%^&*)(]){2}).{8,}$/;
  return regx.test(pw);
 }
document.write(checkPass('PAssword12#$') + "<br>");
document.write(checkPass('PaSsword12#$'));

Note that I used the principle of contrast: (?:[^a-z]*[a-z]){2} matches 2 sequences of symbols other than a-z zero or more times followed by 1 lowercase letter. I modified all the lookaheads the same way.

Sign up to request clarification or add additional context in comments.

Comments

1

Rather than having [A-Z]{2} which will only match two uppercase characters together, you'll have to put in an optional match for any other characters in between two separate ranges (you'll have to do this for the lowercase, numbers and symbols as well). So you would instead put

[A-Z].*?[A-Z]

You also don't actually need to check whether it's at least 8 characters, because any password meeting the criteria for lowercase/uppercase letters, numbers and symbols has to be 8 characters at minimum anyway.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.