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
CodePudding user response:
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
CodePudding user response:
If you don't mind an extra check to make the at least 4 different characters part a bit more flexible, you can use your pattern in combination with a Set.
const regex = /^(?=[^a-z\n]*[a-z])(?=[^\d\n]*\d)[a-z\d]{6,}$/i;
const check = (s) => regex.test(s) && (new Set(s)).size > 3;
[
"abc5",
"abcdef",
"123456",
"aaaaa1",
"aaaa12",
"abcbaa",
"abcdaa",
"aaa123",
"abc1aa",
"1112ab"
].forEach(s =>
console.log(`${s} --> ${check(s) ? "Match" : "No match"}`)
)