js 实现验证码
实现验证码的 JavaScript 方法
生成随机验证码
验证码通常由随机字符(数字、字母或混合)组成。以下代码生成一个 6 位随机验证码(数字和字母混合):
function generateCaptcha() {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let captcha = '';
for (let i = 0; i < 6; i++) {
captcha += chars.charAt(Math.floor(Math.random() * chars.length));
}
return captcha;
}
渲染验证码到页面
将生成的验证码渲染到 HTML 元素中,通常结合 Canvas 实现图形化效果以增强安全性:

function renderCaptcha(captchaText) {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 添加干扰线
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();
}
// 绘制验证码文本
ctx.font = '30px Arial';
ctx.fillStyle = 'black';
ctx.fillText(captchaText, 10, 30);
}
验证用户输入
用户提交表单时,验证输入的验证码是否匹配:

function validateCaptcha(input, storedCaptcha) {
return input.toLowerCase() === storedCaptcha.toLowerCase();
}
完整示例
HTML 结构:
<canvas id="captchaCanvas" width="200" height="50"></canvas>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button onclick="refreshCaptcha()">刷新</button>
<button onclick="checkCaptcha()">验证</button>
JavaScript 逻辑:
let currentCaptcha = generateCaptcha();
// 初始化渲染
renderCaptcha(currentCaptcha);
// 刷新验证码
function refreshCaptcha() {
currentCaptcha = generateCaptcha();
renderCaptcha(currentCaptcha);
}
// 验证逻辑
function checkCaptcha() {
const userInput = document.getElementById('captchaInput').value;
if (validateCaptcha(userInput, currentCaptcha)) {
alert('验证码正确');
} else {
alert('验证码错误');
refreshCaptcha();
}
}
增强安全性措施
- 添加噪声干扰:在 Canvas 绘制时增加随机噪点或扭曲变形。
- 限制尝试次数:记录用户验证失败次数,超过阈值后锁定或延长等待时间。
- 服务端二次验证:即使前端验证通过,仍需在服务器端再次校验。
服务器端集成示例(Node.js)
// 存储生成的验证码(实际应用中应使用Session或Redis)
const captchaStore = {};
app.get('/captcha', (req, res) => {
const captcha = generateCaptcha();
captchaStore[req.sessionID] = captcha;
res.json({ captchaImage: generateCaptchaImage(captcha) });
});
app.post('/verify', (req, res) => {
if (req.body.captcha === captchaStore[req.sessionID]) {
res.json({ success: true });
} else {
res.status(400).json({ error: 'Invalid captcha' });
}
});
注意事项
- 避免使用纯前端验证作为唯一安全措施
- 定期更新验证码生成算法
- 考虑无障碍访问,提供语音验证码选项
- 移动端适配时注意触摸交互体验






