js如何实现验证码
生成验证码
使用Math.random()生成随机数,转换为字符串后截取指定位数。例如生成4位数字验证码:
const code = Math.floor(Math.random() * 9000) + 1000;
绘制图形验证码
通过Canvas API绘制包含干扰元素的图形验证码:

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秒倒计时功能:

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;
}
实际项目中应考虑:
- 验证码时效性控制
- 大小写敏感处理
- 防止暴力破解的频率限制
- 重要操作需配合其他验证方式






