Skip to content Skip to sidebar Skip to footer

Password Validation With Sequential Letters And Numbers - Regex

To have customer accounts more secure, a well crafted password is good practice. This is my Regular Expression string for password validation. /^(?=.*[0-9])(?!.*?\d{3})(?=.*[a-zA-

Solution 1:

You can have a function similar to the below by looping the characters and using a charCodeAt string method as below.

Note: This is for the question raised in below link as well.

string validation for 3 or more consecutive sequential alphanumeric characters in javascript

functionvalidate() {
  var pwd = document.getElementById('password').value;
  var isValid = checkPassword(pwd);
  var elm = document.getElementById('result');
  elm.innerHTML = isValid ? 'Valid' : 'Invalid';
  elm.style.color = isValid ? 'green' : 'red';
}

functioncheckPassword(s) {
    
    if(s) {
       vartest = (x) => !isNaN(x);
       varcheck = (x, y, i) => x + i === y;
    
       for(var i = 0; i < s.length - 2; i++) {
         if(test(s[i])) {
            if(test(s[i + 1]) && test(s[i + 2])) {
              if(check(Number(s[i]),Number(s[i + 1]), 1) &&
                check(Number(s[i]), Number(s[i + 2]), 2)) {
                returnfalse;
              }
            }
         } elseif(!test(s[i + 1]) && !test(s[i + 2])) {
            if(check(s.charCodeAt(i), s.charCodeAt(i + 1), 1) &&
                check(s.charCodeAt(i), s.charCodeAt(i + 2), 2)) {
                returnfalse;
              }
         }
       }
      
    }
    
    returntrue;
}

document.getElementById('buttonToValidate').click();
<inputtype="text"id="password"value="efg123!$" /><inputtype="button"id="buttonToValidate"value="Check"onclick="validate()" /><spanid="result" />

Solution 2:

To add the descending check based on the answer above;

functiontest(s) {
    // Check for sequential numerical charactersfor(var i in s){
      if (+s[+i+1] == +s[i]+1 ) returnfalse;
      if (+s[+i+1]+1 == +s[i] ) returnfalse;
    }

    // Check for sequential alphabetical charactersfor(var i in s){
      if (String.fromCharCode(s.charCodeAt(i)+1) == s[+i+1]) returnfalse;
      if (String.fromCharCode(s.charCodeAt(i)-1) == s[+i+1]) returnfalse;
    }

    returntrue;
  }

// For demo purposes onlyvar tests = [
    'efg123!$',
    'abcd567%',
    'xyz789^&',
    '#hijk23456',
    'ryiiu562@',
    'erty745#',
    'gjnfl45566^',
    '2a3b5c6',
    'mortz',
    '1357911'
], sep = '\t\u2192 ', out = ['Fail','Pass'], eol = '<br>';
document.write('<pre>');
for(var i in tests) document.write(tests[i] + sep + out[+test(tests[i])] + eol);
document.write('</pre>');

Post a Comment for "Password Validation With Sequential Letters And Numbers - Regex"