Regex: “password must have at least 3 of the 4 of the following”

前端 未结 3 1260

I\'m a Regex newbie, and so far have only used it for simple things, like \"must be a number or letter\". Now I have to do something a bit more complex.

I need to u

3条回答
  •  感情败类
    2021-01-05 22:36

    The best way to do this is by checking each condition separately. Performance will suffer if you try to fit all conditional criteria into one expression (see the accepted answer). I also highly recommend against limiting the length of the password to 16 chars — this is extremely insecure for modern standards. Try something more like 64 chars, or even better, 128 — assuming your hashing architecture can handle the load.

    You also didn't specify a language, but this is one way to do it in JavaScript:

    var pws = [
        "%5abCdefg",
        "&5ab",
        "%5abCdef",
        "5Bcdwefg",
        "BCADLKJSDSDFlk"
    ];
    
    function pwCheck(pw) {
        var criteria = 0;
        if (pw.toUpperCase() != pw) {
            // has lower case letters
            criteria++;
        }
        if (pw.toLowerCase() != pw) {
            // has upper case letters
            criteria++;
        }
        if (/^[a-zA-Z0-9]*$/.test(pw) === false) {
            // has special characters
            criteria++;
        }
        if (/\d/.test(pw) === true) {
            // has numbers
            criteria++;
        }
        // returns true if 3 or more criteria was met and length is appropriate
        return (criteria >= 3 && pw.length >= 8 && pw.length <= 16);
    }
    
    pws.forEach(function(pw) {
        console.log(pw + ": " + pwCheck(pw).toString());
    });
    

提交回复
热议问题