1

I have this Regex-Javascript-Code to check a password between 8 to 50 characters which contain at least one lowercase letter, one uppercase letter, one numeric digit, and one special character.

var passwordformat = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,50}$/;

Now, I should have a Redex-Code is only true when at least 2 out of these 4 terms are valid.How can I expend my Regex-Code to achieve this?

I have never programmed a Regex Code. This code is copied out of the net.

pgSystemTester
  • 8,979
  • 2
  • 23
  • 49
  • 1
    Please post examples of input and expected output – mplungjan Sep 30 '20 at 12:57
  • @mplungjan If my password contains at least 2 of this 4 factors(at least one lowercase letter, one uppercase letter, one numeric digit, and one special character.) it should be valid. If not i should return that it is invalid – Sandro Mennel Sep 30 '20 at 12:59
  • 1
    I think you can't do that with a regex. Regexes have no logic and won't count the number of conditions the password satisfies. They only match patterns. You need some additional logic. Also, a super-mega secure super-complex password with hieroglyphs and Mayan symbols is the best way to make your users write it on a post-it an leave it in the eyes of the world, defeating all security purpose. – Jeremy Thille Sep 30 '20 at 12:59
  • 1
    @JeremyThille or just use a password manager – mplungjan Sep 30 '20 at 13:00
  • I would, doesn't mean most users do. I know too many people who write their passwords on post-its. – Jeremy Thille Sep 30 '20 at 13:01
  • 2
    What about using 4 regexes, one for each condition, then check them one after the other? – Christian Baumann Sep 30 '20 at 13:02

1 Answers1

1

This might be hard to swing via a single regex, but is fairly easy to handle via code:

function checkPassword (password) {
    var counter = 0;

    if (/[a-z]/.test(password)) {
        ++counter;
    }
    if (/[A-Z]/.test(password)) {
        ++counter;
    }
    if (/[0-9]/.test(password)) {
        ++counter;
    }
    if (/[^A-Za-z0-9]/.test(password)) {
        ++counter;
    }

    if (counter >= 2 && password.length >= 8 && password.length <= 50) {
        return true;
    }
    else {
        return false;
    }
}

var password = "Aa1@blah";
if (checkPassword(password)) {
    console.log("MATCH");
}

The above logic simply iterates over the 4 password requirements and keeps a counter. A valid password is one which meets at least two criteria and also meets the length requirement.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360