Search code examples
regexpasswords

Check at least 4 different character in password


I need regex that check if a String (password) contains: letters, numbers, at least 6 character (length) AND (this going the problem) at least 4 different characters.

(Password can contains only letters or only numbers but at least 4 different char.)

So far i have been using this but this can not check at least 4 different characters

/^\S(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,}$/i

Thx if u have any Idea


Solution

  • Assuming the string can contain only letters and numbers, an example of a JavaScript regex that fulfills your requirements is:

    const regex = /^(?=.*(.).*(?!\1)(.).*(?!\1|\2)(.).*(?!\1|\2|\3).)[a-z\d]{6,}$/i;
    
    console.log(regex.test('abc'));       // false
    console.log(regex.test('abcbaa'));    // false
    
    console.log(regex.test('abcdaa'));    // true