当前位置:首页 > 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自动登录如何实现

实现自动登录的基本思路 自动登录通常通过结合本地存储(如localStorage或cookie)和token验证机制实现。用户首次登录成功后,服务器返回的认证token会被保存在客户端,下次打开应用时…

h5如何实现定位

h5如何实现定位

使用HTML5 Geolocation API HTML5提供了Geolocation API,可以获取用户的地理位置信息。通过navigator.geolocation对象实现,支持获取经纬度、海拔…

vue项目如何实现

vue项目如何实现

安装Vue.js 通过npm或yarn安装Vue.js。确保Node.js环境已配置完成。 npm install vue # 或 yarn add vue 创建Vue项目 使用Vue CLI工具快…

h5页面如何实现

h5页面如何实现

实现H5页面的方法 H5页面是基于HTML5技术的网页,通常用于移动端和响应式设计。以下是实现H5页面的关键步骤和技术要点。 基础结构 使用HTML5的DOCTYPE声明作为页面的起始。HTML5简…

vue如何实现控制

vue如何实现控制

Vue 实现控制的方法 Vue 提供了多种方式来实现对应用的控制,包括数据绑定、条件渲染、循环渲染、事件处理等。以下是几种常见的控制方法: 数据绑定 通过 v-model 指令实现双向数据绑定,可以…

vue如何实现replaceAll

vue如何实现replaceAll

实现字符串全局替换的方法 在Vue中实现类似JavaScript的replaceAll功能,可以通过以下几种方式: 使用String.prototype.replaceAll()(ES2021+)…