You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不冗余代码的前提下为密码强度检测程序添加等级描述?

Password Strength Validation with Descriptive Labels

First, let's fix a critical issue in your original code: the passwordStrength variable is declared globally, which means its value will persist and accumulate across multiple calls to checkPassword(). We'll move that variable inside the function to reset it each time we validate a new password.

To add the descriptive labels without making the code verbose, we can use a mapping object that directly associates strength percentages with their corresponding descriptions. This approach is clean, easy to read, and simple to modify if you ever need to adjust the labels later.

Here's the updated code:

function checkPassword(password) {
    // Validate input type first
    if (typeof password !== 'string' || password.trim() === '') {
        return 'Only strings are allowed';
    }

    const trimmedPassword = password.trim();
    
    // Check length first to skip unnecessary regex checks if invalid
    if (trimmedPassword.length < 6 || trimmedPassword.length > 12) {
        return 'Password can not be less than 6 or greater than 12 characters';
    }

    // Initialize strength inside the function to avoid cross-call accumulation
    let passwordStrength = 0;
    const validationRules = [
        /[a-z]/,    // Lowercase letters
        /[A-Z]/,    // Uppercase letters
        /[0-9]/,    // Numbers
        /[$@#&!]/   // Special characters
    ];

    // Check each rule and increment strength
    validationRules.forEach(rule => {
        if (rule.test(trimmedPassword)) {
            passwordStrength += 25;
        }
    });

    // Map strength percentage to descriptive label
    const strengthLabels = {
        25: 'poor',
        50: 'weak',
        75: 'medium',
        100: 'strong'
    };

    // Return the matching label
    return strengthLabels[passwordStrength];
}

console.log(checkPassword('@manGaLa')); // Returns 'medium'

Key Improvements:

  • Fixed global variable issue: passwordStrength now lives inside the function, so it resets to 0 for every new password check.
  • Early length validation: We check password length first to avoid wasting time on regex tests if the length is already invalid.
  • Cleaner rule management: Using an array for validation regexes makes it easy to add/remove rules later without rewriting repetitive if statements.
  • Concise label mapping: The strengthLabels object eliminates messy nested if/else chains, making the code more maintainable.

If you want to return both the percentage and description (e.g., "75% (medium)"), just adjust the return line to:

return `${passwordStrength}% (${strengthLabels[passwordStrength]})`;

内容的提问来源于stack exchange,提问作者danoseun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:56:23