当前位置:首页 > JavaScript

js如何实现验证码

2026-01-30 20:03:06JavaScript

生成验证码

使用Math.random()生成随机数,转换为字符串后截取指定位数。例如生成4位数字验证码:

const code = Math.floor(Math.random() * 9000) + 1000;

绘制图形验证码

通过Canvas API绘制包含干扰元素的图形验证码:

js如何实现验证码

function generateCaptcha() {
  const canvas = document.getElementById('captcha');
  const ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 生成随机字符串
  const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  let captcha = '';
  for (let i = 0; i < 4; i++) {
    captcha += chars.charAt(Math.floor(Math.random() * chars.length));
  }

  // 绘制背景和文字
  ctx.fillStyle = '#f3f3f3';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  ctx.font = '24px Arial';
  ctx.fillStyle = '#333';
  ctx.fillText(captcha, 10, 25);

  // 添加干扰线
  ctx.strokeStyle = '#ccc';
  for (let i = 0; i < 5; i++) {
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  return captcha;
}

验证逻辑实现

将生成的验证码存储在变量或SessionStorage中,提交时进行比对:

let storedCaptcha = generateCaptcha(); // 初始化验证码

document.getElementById('verify-btn').addEventListener('click', () => {
  const userInput = document.getElementById('captcha-input').value;
  if (userInput === storedCaptcha) {
    alert('验证成功');
  } else {
    alert('验证码错误');
    storedCaptcha = generateCaptcha(); // 刷新验证码
  }
});

短信/邮件验证码

使用定时器实现60秒倒计时功能:

js如何实现验证码

let countdown = 60;
const timer = setInterval(() => {
  countdown--;
  document.getElementById('sms-btn').innerText = `${countdown}s`;
  if (countdown <= 0) {
    clearInterval(timer);
    document.getElementById('sms-btn').innerText = '获取验证码';
    document.getElementById('sms-btn').disabled = false;
  }
}, 1000);

安全性增强措施

建议将验证码有效期设置为5分钟,服务端进行二次验证:

// 服务端存储示例(Node.js)
const captchaMap = new Map();

function generateServerCaptcha() {
  const code = Math.random().toString(36).substr(2, 6).toUpperCase();
  captchaMap.set(code, {
    code,
    expires: Date.now() + 300000 // 5分钟过期
  });
  return code;
}

实际项目中应考虑:

  • 验证码时效性控制
  • 大小写敏感处理
  • 防止暴力破解的频率限制
  • 重要操作需配合其他验证方式

分享给朋友:

相关文章

vue底层如何实现

vue底层如何实现

Vue 底层的核心实现机制 Vue 的底层实现主要围绕响应式系统、虚拟 DOM 和组件化架构展开。以下是关键技术的详细解析: 响应式系统 依赖追踪与发布订阅模式 通过 Object.definePr…

vue如何实现两栏布局

vue如何实现两栏布局

使用Flexbox实现两栏布局 Flexbox是CSS3中强大的布局方式,可以轻松实现两栏布局。在Vue中可以直接在组件的style标签中使用。 <template> <div…

h5如何实现vr效果

h5如何实现vr效果

使用WebXR API实现VR效果 WebXR是浏览器中实现VR/AR的核心API,支持设备姿态追踪、渲染交互等功能。需在支持WebXR的设备(如Oculus、HTC Vive)或浏览器模拟环境中运行…

vue如何实现mvvm

vue如何实现mvvm

Vue 的 MVVM 实现原理 Vue 通过数据绑定和响应式系统实现 MVVM(Model-View-ViewModel)模式。其核心在于将数据模型(Model)与视图(View)通过 ViewMod…

vue如何实现tap

vue如何实现tap

Vue 中实现类似移动端 tap 事件的方法 在 Vue 中可以通过以下几种方式实现类似移动端 tap(轻触)事件的效果: 使用第三方库 安装 v-tap 指令库可以快速实现 tap 事件:…

react如何实现插槽

react如何实现插槽

React 实现插槽的方法 React 本身没有直接提供类似 Vue 的插槽(slot)概念,但可以通过以下几种方式实现类似功能: 使用 props.children React 组件可以通过 pr…