js实现登录验证码
实现登录验证码的步骤
生成随机验证码
验证码通常由数字、字母或组合构成,使用Math.random()生成随机字符。以下是一个生成4位数字验证码的示例:

function generateCaptcha() {
const captchaLength = 4;
let captcha = '';
for (let i = 0; i < captchaLength; i++) {
captcha += Math.floor(Math.random() * 10);
}
return captcha;
}
const currentCaptcha = generateCaptcha();
渲染验证码到页面
将生成的验证码显示在页面上,可通过Canvas或纯文本实现。以下是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 = '#000';
ctx.fillText(captchaText, 10, 30);
}
renderCaptcha(currentCaptcha);
验证用户输入
在提交表单时比对用户输入与生成的验证码:
document.getElementById('loginForm').addEventListener('submit', function(e) {
e.preventDefault();
const userInput = document.getElementById('captchaInput').value;
if (userInput !== currentCaptcha) {
alert('验证码错误,请重新输入');
// 刷新验证码
currentCaptcha = generateCaptcha();
renderCaptcha(currentCaptcha);
return false;
}
// 验证通过后继续登录流程
this.submit();
});
添加刷新功能
提供验证码刷新按钮以提升用户体验:
document.getElementById('refreshCaptcha').addEventListener('click', function() {
currentCaptcha = generateCaptcha();
renderCaptcha(currentCaptcha);
});
完整HTML结构示例
<div>
<canvas id="captchaCanvas" width="120" height="40"></canvas>
<button id="refreshCaptcha">刷新验证码</button>
</div>
<input type="text" id="captchaInput" placeholder="输入验证码">
增强安全性建议
- 服务端二次验证:即使前端验证通过,仍需在服务器端再次校验验证码有效性
- 设置有效期:验证码应在生成后2-5分钟内失效
- 限制尝试次数:防止暴力破解,超过3次错误需重新生成
- 使用库生成复杂验证码:如
svg-captcha库可生成图形扭曲的验证码
注意事项
- 避免纯数字验证码:建议混合大小写字母增加复杂度
- 禁用右键查看元素:防止通过DOM获取验证码内容
- 考虑无障碍访问:为视觉障碍用户提供语音验证码备选方案






