Back to js-conditionals
09-password-strength.js
JavaScript
1/**
2 * 🔒 SecureApp Password Checker
3 *
4 * You're building the signup page for SecureApp, a new productivity tool.
5 * The product manager wants a password strength meter that gives users
6 * real-time feedback as they type their password.
7 *
8 * The checker evaluates 5 criteria:
9 * 1. At least 8 characters long
10 * 2. Contains at least one uppercase letter (A-Z)
11 * 3. Contains at least one lowercase letter (a-z)
12 * 4. Contains at least one number (0-9)
13 * 5. Contains at least one special character (!@#$%^&*()_+-=[]{}|;:,.<>?)
14 *
15 * Strength levels based on how many criteria are met:
16 * - 0–1 criteria → "weak"
17 * - 2–3 criteria → "medium"
18 * - 4 criteria → "strong"
19 * - All 5 → "very strong"
20 *
21 * Rules:
22 * - Empty string → "weak"
23 * - Non-string input → "weak"
24 *
25 * @param {string} password - The password to evaluate
26 * @returns {string} "weak", "medium", "strong", or "very strong"
27 */
28export function checkPasswordStrength(password) {
29
30 function hasUpperCase(pass) {
31 return /[A-Z]/.test(pass);
32 }
33
34 function hasLowerCase(pass) {
35 return /[a-z]/.test(pass);
36 }
37
38 function hasNumber(pass){
39 return /\d/.test(pass)
40 }
41
42 function hasSpecialChar(pass){
43 return /[!@#$%^&*()_+\-=\[\]{}|;:,.<>?]/.test(pass);
44 }
45
46 if(typeof password !== "string") {
47 return "weak"
48 }
49 password = password.trim()
50
51 if(password === ""){
52 return "weak"
53 }
54
55 let criteriaNum = 0;
56
57 if(password.length >= 8 ){
58 criteriaNum ++
59 }
60
61 if(hasUpperCase(password)){
62 criteriaNum += 1
63 }
64
65 if(hasLowerCase(password)){
66 criteriaNum += 1
67 }
68
69 if(hasNumber(password)){
70 criteriaNum += 1
71 }
72
73 if(hasSpecialChar(password)){
74 criteriaNum += 1
75 }
76
77 if(criteriaNum === 5){
78 return "very strong"
79 }else if(criteriaNum === 4) {
80 return "strong"
81 } else if (criteriaNum >= 2){
82 return "medium"
83 }else {
84 return "weak"
85 }
86}
87