0

I am having a password change page where I want to validate my password with "2 small letters, 2 capital letters, 3 symbols, 2 digits and so on. Now from the below code I am able to just validate the password in sequence like "aa, KK,ap, JK, 90, 89" but not working for " aK9Ju, a^rtH, hGT5$u etc.

I am just pasting code for small letters, If you want I can provide the entire code.

psw.onkeyup = function() { var LC = jsonData.LOWERCASE; var psw = document.getElementById("psw").value.replace(/([a-z])\d+/g, '$1'); var lowerCaseLetters = new RegExp('[a-z]{' + LC + '}', 'g') if(psw.match(lowerCaseLetters)) { letter.classList.remove("invalid"); letter.classList.add("valid"); } else { letter.classList.remove("valid"); letter.classList.add("invalid"); } 

So, My requirement is what ever the way I put my password it should validate the same.

0

1 Answer 1

0

I've created you a working example with 3 restraints: - 2 small letters - 2 capital letters - 2 digits if you need to add a constraint, yjust write a simple regex to match that single constraint, and connect it to the existing if statement via &&. I've used a function to count the number of occurences of regex matches from here.

function testPassword(){ var pw = document.getElementById("password").value; if ( count(pw, /[a-z]/g) > 1 && count(pw, /[A-Z]/g) > 1 && count(pw, /[0-9]/g) > 1 && count(pw,/\W|_/g) > 1 //special chars ){ alert("success") } } const count = (str,pattern) => { const re = pattern return ((str || '').match(re) || []).length }
<input id="password" type="text"> <input type="submit" id="submit" onClick="testPassword()">

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

1 Comment

Found the answer, below code is working.. psw.onkeyup = function() { var LC = jsonData.LOWERCASE; var lowerCaseLetters = new RegExp('(?:[a-z].*){' + LC + '}', 'g') if(psw.value.match(lowerCaseLetters)) { letter.classList.remove("invalid"); letter.classList.add("valid"); } else { letter.classList.remove("valid"); letter.classList.add("invalid"); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.