2+ out of 4 conditions regex

后端 未结 2 518
我寻月下人不归
我寻月下人不归 2021-01-16 11:07

I have 4 requirements for user passwords:

  • At least 1 a-z char
  • At least 1 A-Z char
  • At least 1 0-9 char
  • At least 1 symbol in .
相关标签:
2条回答
  • 2021-01-16 11:38

    You can use following expression:

    /[a-z]/.test(pass)+/[A-Z]/.test(pass)+/\d/.test(pass)+/[.!@#$%^&*()_]/.test(pass)>2
    
    0 讨论(0)
  • 2021-01-16 11:43

    Always break down big problems into smaller ones.

    Define a separate Regex for each of your four different conditions, then check if enough of them are fulfilled.

    For example:

    var checks = {
        lowercase: /[a-z]/,
        uppercase: /[A-Z]/,
        number: /[0-9]/,
        symbol: /[.!@#$%^&*()_]/
    }, passcount = 0, results = {};
    for( var k in checks) if( checks.hasOwnProperty(k)) {
        if( checks[k].test(password)) {
            passcount++;
            results[k] = true;
        }
        else results[k] = false;
    }
    if( passcount < 2) {
        alert("Your password didn't meet enough conditions.\n" +
          "[Provide useful info here - 'results' object lists " +
          "whether each test passed or failed, so use that for " +
          "a user-friendly experience!]");
        return false;
    }
    return true;
    

    And finally, obligatory xkcd comic:

    xkcd

    0 讨论(0)
提交回复
热议问题