Practice: Password Checker
Rules and scores.
Sign up forms check your password as you type. Is it long enough? Does it have a number, a capital, a symbol? Let's build that check as a function that returns a score, and a list of tips.

- Sign up forms check passwords
- Length, numbers, capitals
- A score and tips
Rules as data
Each rule is an object with a test and a tip. The tests are small functions, some using regular expressions. Check runs every rule. The passed rules add to the score, and the failed ones give their tips. Keeping rules as data means adding a new rule is just one more line. Run it.
const rules = [
{ test: p => p.length >= 8, tip: "use at least 8 characters" },
{ test: p => /[A-Z]/.test(p), tip: "add a capital letter" },
{ test: p => /\d/.test(p), tip: "add a number" },
{ test: p => /[^\w\s]/.test(p), tip: "add a symbol" },
];
function check(password) {
const failed = rules.filter(r => !r.test(password));
const score = rules.length - failed.length;
return { score, tips: failed.map(r => r.tip) };
}
for (const p of ["cat", "sunshine2", "Sunsh1ne!"]) {
const { score, tips } = check(p);
console.log(`${p}: ${score}/4`, tips.length ? "-> " + tips.join(", ") : "strong");
}cat: 0/4 -> use at least 8 characters, add a capital letter, add a number, add a symbol sunshine2: 2/4 -> add a capital letter, add a symbol Sunsh1ne!: 4/4 strong
Ideas to extend it
You could connect this to an input event, so the score updates as the user types. Show the score as a coloured bar. Or add a rule that rejects very common passwords, using a set of banned words. The logic stays the same. Only the display changes.
| key | value |
|---|---|
| rules array | easy to extend |
| filter | find failed rules |
| Destructuring | { score, tips } |
| Next step | hook to input event |
Summary
Storing rules as data, and filtering them, made the password checker short and easy to extend. Next, a temperature converter on a web page.
Key takeaways- Rules as objects
- filter failed rules
- score and tips