Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
567 views
in Technique[技术] by (71.8m points)

javascript - 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-Z])(?!.*?[a-zA-Z]{3})(?=.*[~!@#$%^&*()+-?])([a-zA-Z0-9~!@#$%^&*()+-?]{8,})$/

Represents:

  • 8 or more characters.
  • Uppercase letter A-Z
  • Lowercase letters a-z
  • Special characters ~!@#$%^&*()+-?
  • What is this Regular Expression function for this?: Must not contain up to 3 sequential letters and/or numbers.

Having numbers and/or letters in order 3 or more sequential is not OK.

Example:

Not OK = efg123!$, abcd567%, xyz789^&, #hijk23456
OK = ryiiu562@, erty745#, gjnfl45566^

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = '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>');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...