当前位置:首页 > JavaScript

js实现登录验证码

2026-03-01 09:04:50JavaScript

实现登录验证码的步骤

生成验证码

使用Canvas绘制随机验证码,包含数字、字母或混合字符。以下是一个生成4位随机验证码的示例:

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

  const canvas = document.getElementById('captchaCanvas');
  const ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.font = '30px Arial';
  ctx.fillStyle = '#000';
  ctx.fillText(captcha, 10, 30);

  return captcha;
}

存储验证码

将生成的验证码存储在变量或sessionStorage中,用于后续验证:

let currentCaptcha = generateCaptcha();

// 或者使用sessionStorage
sessionStorage.setItem('captcha', currentCaptcha);

验证用户输入

在提交表单时比较用户输入的验证码和存储的验证码:

function validateCaptcha() {
  const userInput = document.getElementById('captchaInput').value;
  const storedCaptcha = sessionStorage.getItem('captcha');

  if (userInput.toUpperCase() !== storedCaptcha) {
    alert('验证码错误');
    currentCaptcha = generateCaptcha();
    return false;
  }
  return true;
}

刷新验证码

提供刷新验证码的功能:

document.getElementById('refreshCaptcha').addEventListener('click', function() {
  currentCaptcha = generateCaptcha();
});

HTML结构示例

<canvas id="captchaCanvas" width="120" height="40"></canvas>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button id="refreshCaptcha">刷新验证码</button>

增强安全性措施

  • 添加干扰线和噪点
  • 限制验证码尝试次数
  • 设置验证码有效期
// 添加干扰线
function addNoise(ctx) {
  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()*120, Math.random()*40);
    ctx.lineTo(Math.random()*120, Math.random()*40);
    ctx.stroke();
  }
}

服务器端验证

虽然前端验证可以提高用户体验,但必须配合服务器端验证:

js实现登录验证码

// 伪代码示例
app.post('/login', (req, res) => {
  if (req.body.captcha !== req.session.captcha) {
    return res.status(400).send('验证码错误');
  }
  // 继续登录流程
});

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

相关文章

vue实现验证码

vue实现验证码

Vue 实现验证码的方法 使用 Canvas 生成图形验证码 安装依赖(如需要): npm install vue-canvas-verify --save 创建验证码组件: <te…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现瀑布流

js实现瀑布流

实现瀑布流布局 瀑布流布局是一种常见的网页布局方式,常用于图片展示、商品列表等场景。以下是使用 JavaScript 实现瀑布流布局的几种方法。 纯 JavaScript 实现 通过计算元素的位置和…

js实现变形

js实现变形

使用 CSS 和 JavaScript 实现元素变形 在 JavaScript 中实现变形效果通常结合 CSS 的 transform 属性,通过动态修改该属性实现元素的旋转、缩放、倾斜或平移。 基…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…