js实现简单的验证码
实现简单验证码的步骤
生成随机验证码
使用 Math.random() 生成随机字符串,通常包含数字和字母组合:
function generateCaptcha() {
const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
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 = '#f0f0f0';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制验证码文本
ctx.font = '30px Arial';
ctx.fillStyle = '#000';
ctx.fillText(captchaText, 10, 30);
// 添加干扰线
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();
}
}
验证用户输入
比较用户输入与生成的验证码(不区分大小写):
function validateCaptcha(inputValue, storedCaptcha) {
return inputValue.toLowerCase() === storedCaptcha.toLowerCase();
}
完整示例
HTML 结构:
<canvas id="captchaCanvas" width="200" height="50"></canvas>
<input type="text" id="captchaInput" placeholder="输入验证码">
<button id="refreshCaptcha">刷新</button>
<button id="submitCaptcha">提交</button>
<p id="captchaResult"></p>
JavaScript 逻辑:

let currentCaptcha = generateCaptcha();
document.addEventListener('DOMContentLoaded', () => {
drawCaptcha(currentCaptcha);
document.getElementById('refreshCaptcha').addEventListener('click', () => {
currentCaptcha = generateCaptcha();
drawCaptcha(currentCaptcha);
});
document.getElementById('submitCaptcha').addEventListener('click', () => {
const userInput = document.getElementById('captchaInput').value;
const resultElement = document.getElementById('captchaResult');
if (validateCaptcha(userInput, currentCaptcha)) {
resultElement.textContent = '验证成功!';
resultElement.style.color = 'green';
} else {
resultElement.textContent = '验证失败,请重试!';
resultElement.style.color = 'red';
currentCaptcha = generateCaptcha();
drawCaptcha(currentCaptcha);
}
});
});
增强安全性建议
- 服务端二次验证:前端验证可被绕过,重要操作需在服务端再次验证
- 增加过期时间:设置验证码有效期(如5分钟)
- 限制尝试次数:防止暴力破解
- 使用更复杂图形:扭曲文字、背景干扰等
这种方法实现了基础的前端验证码功能,适合简单场景使用。对于高安全需求,建议结合后端验证机制。






