How to check password strength
Short answer
Describe each rule as a regular expression and collect the messages for the rules that fail:
const rules = [
[/.{8,}/, 'at least 8 characters'],
[/[a-z]/, 'a lowercase letter'],
[/[A-Z]/, 'an uppercase letter'],
[/\d/, 'a digit'],
];
const checkPassword = (password) => rules.filter(([pattern]) => !pattern.test(password)).map(([, message]) => message);
console.log(checkPassword('hello'));
console.log(checkPassword('Hello2025'));Output:
[
"at least 8 characters",
"an uppercase letter",
"a digit"
]
[]A strength score
Count the met rules and turn the number into a word for a strength indicator:
const strength = (password) => {
let score = 0;
if (password.length >= 8) score++;
if (password.length >= 12) score++;
if (/[a-z]/.test(password) && /[A-Z]/.test(password)) score++;
if (/\d/.test(password)) score++;
if (/[^a-zA-Z0-9]/.test(password)) score++;
return ['very weak', 'weak', 'fair', 'good', 'strong', 'very strong'][score];
};
console.log(strength('abc'));
console.log(strength('Summer2025'));
console.log(strength('Tr1cky-Passw0rd!'));Output:
very weak
good
very strongCommon mistake
Rules alone do not make a password safe: Password1 passes all of them, but it is one of the most common passwords. Length matters more than complexity, and the server must store only a hash of the password.
const rules = [/.{8,}/, /[a-z]/, /[A-Z]/, /\d/];
console.log(rules.every((pattern) => pattern.test('Password1')));Output:
trueFunctions used in this recipe
- RegExp.prototype.test — Checks whether a string matches a pattern.
- Array.prototype.filter — Creates a new array from the elements that pass a test.