Password Validation with Sequential Letters and Numbers - RegEx

断了今生、忘了曾经 提交于 2019-11-28 12:57:57

There's no way using RegEx that I know of, but here is a naive functional approach.

First, loop through the string and compare each character against the next two characters by adding +1 and +2 to the current index and comparing appropriately.

Second, loop through the string again and compare checks the next two characters against the current character to see if they are sequential.

If both loops fail to find sequential characters, the function returns true, otherwise it returns false.

The first four return false (fail), while the last three return true (pass).

function test(s) {
    // Check for sequential numerical characters
    for(var i in s) 
        if (+s[+i+1] == +s[i]+1 && 
            +s[+i+2] == +s[i]+2) return false;
    // Check for sequential alphabetical characters
    for(var i in s) 
        if (String.fromCharCode(s.charCodeAt(i)+1) == s[+i+1] && 
            String.fromCharCode(s.charCodeAt(i)+2) == s[+i+2]) return false;
    return true;
}

// For demo purposes only
var tests = [
    'efg123!$',
    'abcd567%',
    'xyz789^&',
    '#hijk23456',
    'ryiiu562@',
    'erty745#',
    'gjnfl45566^'
], 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>');

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

function validate() {
  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';
}

function checkPassword(s) {
    
    if(s) {
       var test = (x) => !isNaN(x);
       var check = (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(s[i], s[i + 1], 1) &&
                check(s[i], s[i + 2], 2)) {
                return false;
              }
            }
         } else if(!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)) {
                return false;
              }
         }
       }
      
    }
    
    return true;
}

document.getElementById('buttonToValidate').click();
<input type="text" id="password" value="efg123!$" /> 
<input type="button" id="buttonToValidate" value="Check" onclick="validate()" />
<span id="result" />
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!