js登录验证码实现
验证码生成与实现
在JavaScript中实现登录验证码功能通常涉及生成随机验证码字符串、绘制图形干扰元素以及验证用户输入。以下是完整的实现方法:
生成随机验证码字符串
使用以下代码生成4-6位的随机验证码(数字+字母组合):
function generateCaptcha() {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let captcha = '';
for (let i = 0; i < 6; i++) {
const randomIndex = Math.floor(Math.random() * chars.length);
captcha += chars[randomIndex];
}
return captcha;
}
绘制验证码图像
通过Canvas绘制包含干扰元素的验证码图像:

function drawCaptcha(captchaText) {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
// 清除画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 背景色
ctx.fillStyle = '#f5f5f5';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制验证码文本
ctx.font = '30px Arial';
ctx.fillStyle = '#333';
for (let i = 0; i < captchaText.length; i++) {
ctx.fillText(
captchaText[i],
15 + i * 25,
30 + Math.random() * 10
);
}
// 添加干扰线
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();
}
}
HTML结构示例
<div class="captcha-container">
<canvas id="captchaCanvas" width="200" height="50"></canvas>
<button id="refreshCaptcha">刷新</button>
<input type="text" id="captchaInput" placeholder="输入验证码">
</div>
验证逻辑实现
let currentCaptcha = generateCaptcha();
// 初始化验证码
drawCaptcha(currentCaptcha);
// 刷新验证码
document.getElementById('refreshCaptcha').addEventListener('click', () => {
currentCaptcha = generateCaptcha();
drawCaptcha(currentCaptcha);
});
// 验证函数
function validateCaptcha() {
const userInput = document.getElementById('captchaInput').value;
if (userInput.toUpperCase() === currentCaptcha) {
alert('验证码正确');
return true;
} else {
alert('验证码错误');
currentCaptcha = generateCaptcha();
drawCaptcha(currentCaptcha);
return false;
}
}
增强安全性的措施
- 服务端二次验证:即使前端验证通过,仍需在提交表单时在服务器端重新验证
- 限制尝试次数:记录IP或用户尝试次数,防止暴力破解
- 动态变形:对验证码字符进行旋转、扭曲等变形处理
- 过期时间:设置验证码有效期(通常3-5分钟)
完整示例调用
// 页面加载时初始化
window.onload = function() {
currentCaptcha = generateCaptcha();
drawCaptcha(currentCaptcha);
// 表单提交时验证
document.getElementById('loginForm').onsubmit = function(e) {
if (!validateCaptcha()) {
e.preventDefault();
}
};
};
通过以上方法可以实现基础的前端验证码功能,但需注意真正的安全验证必须依赖服务端实现。






