0

I need to figure out if a password meets several conditions, but not all.

Has to include 3 out 4 conditions

a) A-Z
b) a-z
c) 0-9
d) !*?$%&

So it's correct if the password has a capital letter, a lower letter and a numnber or instead of the number a special char, ...

Is this possible without writing several OR conditions (a+b+c OR a+b+d OR a+c+d OR b+c+d) ?

Dinkheller
  • 4,631
  • 5
  • 39
  • 67

3 Answers3

2

I'd avoid the issue of using a single regular expression, and simply combine the simple regular expressions together into an array, test the entered-password against that array of expressions using Array.prototype.filter() to create a new array from those matches where the individual regular expressions test true (using RegExp.prototype.test()):

function validateConditions (string, n) {
    // individual tests:
    var capital = /[A-Z]/, // any letter, from the characters A-Z (inclusive)
        lower = /[a-z]/, // any letter, from the characters a-z (inclusive)
        numeric = /\d/, // any number character
        special = /[!*?$%&]/, // any of these special characters

    // an array of those simple tests:
        tests = [capital, lower, numeric, special],
    // filtering the array of tests (to create a new array 'success'):
        success = tests.filter(function (validate) {
            // if the string tests true (RegExp.test returns a Boolean value):
            if (validate.test(string)) {
                // we return true (though any value would be fine, since
                // we're only checking the length of the 'success' array):
                return true;
            }
        });

    // making sure that the 'success' array has a length equal to, or greater
    // than the required number ('n') of matches:
    return success.length >= n;
}

// adding an event-listener to the 'test' element, which runs on 'keyup':
document.getElementById('test').addEventListener('keyup', function (e) {
    // logging the returned Boolean of validateConditions():
    console.log(validateConditions(e.target.value, 3));
});

JS Fiddle demo.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
2

This website might give some answers too: http://www.zorched.net/2009/05/08/password-strength-validation-with-regular-expressions/

On a side note: Use of symbols, lowercase, uppercase, numbers does increase entropy, but length is much more important. The CorrectHorseBatteryStaple (http://xkcd.com/936/) example was a big eye-opener to me.

Taco Jan Osinga
  • 2,510
  • 1
  • 16
  • 11
0

Look into using regular expression lookaheads and see if you can hack together a beast of a regex. I checked google for "regex password complexity" and found similar questions to yours, so I'd start there.

Paul
  • 646
  • 4
  • 13
  • Lookaheads is interesting but not the solution. Solution was found at: http://stackoverflow.com/questions/3466850/complex-password-regular-expression – Dinkheller Nov 19 '14 at 00:26