Skip to content

密码 Strength Checker

简单 约 25 分钟

你将构建什么

`checkPassword(密码)` 函数那个返回 'weak', '中等', or 'strong' based on 长度, presence 的 uppercase, lowercase, 数字, and 特殊 characters.

学习目标

  • 组合多个条件 using 布尔值 logic
  • Use 字符串方法到 inspect character 类型
  • 构建 scoring 系统那个 aggregates 检查
  • 返回 meaningful feedback based on score

前置要求

  • 字符串方法 (长度, character access)
  • 如果/else conditional 语句
  • 布尔值 logic 使用 && and ||

步骤

  1. 1

    检查长度

    开始通过检查如果密码是 at 最少 8 characters 长. 长度是 大多数基础 strength indicator. 创建变量 score 开始 at 0 and 添加点 for 长度.

    代码
    function checkPassword(password) {
      let score = 0;
      if (password.length >= 8) score += 1;
      if (password.length >= 12) score += 1;
      return score;
    }

    预期结果

    checkPassword('短') 返回 0; checkPassword('longpassword') 返回 1.

  2. 2

    检查 for character variety

    Use regular 表达式到 检查 for uppercase letters, lowercase letters, 数字, and 特殊 characters. 每个类型找到添加点 到 score.

    代码
      if (/[a-z]/.test(password)) score += 1;
      if (/[A-Z]/.test(password)) score += 1;
      if (/[0-9]/.test(password)) score += 1;
      if (/[^a-zA-Z0-9]/.test(password)) score += 1;

    预期结果

    密码使用所有 four 类型获取 4 extra 点.

  3. 3

    映射 score 到 strength label

    Convert numeric score 到 human-readable label: score <= 2 是 'weak', 3-4 是 '中等', 5+ 是 'strong'. 返回 label 相反的 raw score.

    代码
      if (score <= 2) return 'weak';
      if (score <= 4) return 'medium';
      return 'strong';

    预期结果

    checkPassword('abc') 返回 'weak'; checkPassword('Abc123!@') 返回 'strong'.

  4. 4

    测试使用各种密码

    Call 函数使用几个测试密码到 验证 scoring 工作正确地跨越不同 combinations.

    代码
    console.log(checkPassword('123'));           // weak
    console.log(checkPassword('abcdefgh'));     // weak
    console.log(checkPassword('Abcd1234'));     // medium
    console.log(checkPassword('Str0ng!Pass#')); // strong

    预期结果

    Four 行: weak, weak, 中等, strong.

  5. 5

    添加输入验证

    在主逻辑入口处添加输入验证:检查输入是否为有效数字、是否在允许范围内,对非法输入给出清晰提示而非崩溃。这是健壮程序的第一道防线。

    代码
    function validateInput(value, min, max) {
      if (typeof value !== "number" || Number.isNaN(value)) {
        throw new Error(`Invalid input: ${value} is not a number`);
      }
      if (value < min || value > max) {
        throw new Error(`Input ${value} out of range [${min}, ${max}]`);
      }
      return value;
    }
    
    // Usage
    const input = validateInput(rawInput, 1, 100);

    预期结果

    非法输入(非数字或超出范围)会抛出清晰的错误信息,合法输入正常通过。

自己动手试试

你学到了什么

你组合多个布尔值条件到 scoring 系统 and used regular 表达式到 inspect 字符串内容 — 模式 used in 真实-世界 validation logic.

相关资源

相关课程

相关练习

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题