当前位置:首页 > JavaScript

用js实现验证码

2026-04-04 09:35:14JavaScript

用js实现验证码

验证码生成与验证实现

生成随机验证码字符串

function generateCaptcha(length = 6) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let captcha = '';
  for (let i = 0; i < length; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return captcha;
}

绘制图形验证码

function drawCaptcha(canvasId, captchaText) {
  const canvas = document.getElementById(canvasId);
  const ctx = canvas.getContext('2d');

  // 清除画布
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 背景色
  ctx.fillStyle = '#f5f5f5';
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 绘制干扰线
  for (let i = 0; i < 5; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 绘制验证码文本
  for (let i = 0; i < captchaText.length; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`;
    ctx.font = `${20 + Math.random() * 10}px Arial`;
    ctx.fillText(
      captchaText[i],
      10 + i * 25,
      30 + Math.random() * 10
    );
  }
}

验证用户输入

function validateCaptcha(inputId, storedCaptcha) {
  const userInput = document.getElementById(inputId).value;
  return userInput === storedCaptcha;
}

完整示例实现

<!DOCTYPE html>
<html>
<head>
  <title>验证码示例</title>
  <style>
    #captchaCanvas {
      border: 1px solid #ddd;
      margin: 10px 0;
    }
    button {
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div>
    <canvas id="captchaCanvas" width="200" height="50"></canvas>
    <button onclick="refreshCaptcha()">刷新验证码</button>
  </div>
  <div>
    <input type="text" id="captchaInput" placeholder="请输入验证码">
    <button onclick="checkCaptcha()">验证</button>
  </div>
  <p id="result"></p>

  <script>
    let currentCaptcha = '';

    function initCaptcha() {
      currentCaptcha = generateCaptcha();
      drawCaptcha('captchaCanvas', currentCaptcha);
    }

    function refreshCaptcha() {
      currentCaptcha = generateCaptcha();
      drawCaptcha('captchaCanvas', currentCaptcha);
      document.getElementById('result').textContent = '';
    }

    function checkCaptcha() {
      const isValid = validateCaptcha('captchaInput', currentCaptcha);
      document.getElementById('result').textContent = isValid 
        ? '验证通过' 
        : '验证码错误';
    }

    // 初始化
    window.onload = initCaptcha;
  </script>
</body>
</html>

安全增强建议

  1. 服务端应存储验证码并与用户提交的进行比对
  2. 设置验证码过期时间(通常1-5分钟)
  3. 限制验证码尝试次数防止暴力破解
  4. 考虑添加滑动验证等更复杂的验证方式

服务端验证示例(Node.js)

const express = require('express');
const session = require('express-session');
const app = express();

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: true
}));

// 生成验证码接口
app.get('/captcha', (req, res) => {
  const captcha = generateCaptcha();
  req.session.captcha = captcha;
  req.session.captchaExpire = Date.now() + 300000; // 5分钟后过期

  // 这里应该返回图形验证码,简化示例只返回文本
  res.json({ captcha });
});

// 验证接口
app.post('/validate', express.json(), (req, res) => {
  const { captcha } = req.body;
  if (!req.session.captcha || Date.now() > req.session.captchaExpire) {
    return res.json({ valid: false, message: '验证码已过期' });
  }

  const isValid = captcha === req.session.captcha;
  if (isValid) {
    req.session.captcha = null; // 验证成功后清除
  }

  res.json({ valid: isValid });
});

app.listen(3000, () => console.log('Server running on port 3000'));

标签: 验证码js
分享给朋友:

相关文章

验证码实现vue

验证码实现vue

验证码实现(Vue) 在Vue中实现验证码功能通常需要结合前端生成和验证逻辑,以及可能的后端校验。以下是两种常见实现方式: 基于Canvas的图形验证码 通过Canvas动态生成包含随机字符的图形验…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含inpu…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

vue实现js休眠

vue实现js休眠

实现 JavaScript 休眠的方法 在 Vue 中实现 JavaScript 休眠(延迟执行)可以通过以下方式实现。由于 JavaScript 本身没有内置的 sleep 函数,通常使用 Prom…

js实现吸色

js实现吸色

使用Canvas实现吸色功能 通过Canvas的getImageData方法获取像素颜色数据。创建一个Canvas元素,将目标图像绘制到Canvas上,通过鼠标事件获取坐标对应的颜色值。 c…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…