js 实现验证码
实现验证码功能
验证码通常用于防止自动化操作,如机器人提交表单。以下是使用JavaScript实现简单验证码的方法。
生成随机验证码
创建一个函数生成随机字母和数字组合的验证码:
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;
}
显示验证码
将生成的验证码显示在页面上:
function displayCaptcha() {
const captcha = generateCaptcha();
document.getElementById('captchaDisplay').textContent = captcha;
return captcha; // 返回用于验证
}
验证用户输入
检查用户输入的验证码是否正确:
function validateCaptcha(userInput, correctCaptcha) {
return userInput === correctCaptcha;
}
完整示例
HTML部分:
<div id="captchaDisplay"></div>
<input type="text" id="userCaptcha" placeholder="输入验证码">
<button onclick="checkCaptcha()">验证</button>
<button onclick="refreshCaptcha()">刷新</button>
<p id="result"></p>
JavaScript部分:
let currentCaptcha = '';
window.onload = function() {
currentCaptcha = displayCaptcha();
};
function refreshCaptcha() {
currentCaptcha = displayCaptcha();
document.getElementById('userCaptcha').value = '';
document.getElementById('result').textContent = '';
}
function checkCaptcha() {
const userInput = document.getElementById('userCaptcha').value;
const isValid = validateCaptcha(userInput, currentCaptcha);
const resultElement = document.getElementById('result');
if (isValid) {
resultElement.textContent = '验证码正确';
resultElement.style.color = 'green';
} else {
resultElement.textContent = '验证码错误';
resultElement.style.color = 'red';
}
}
增强安全性
为了增加安全性,可以考虑以下改进:
- 在服务器端进行最终验证
- 添加扭曲文字或干扰线等视觉障碍
- 使用Canvas绘制验证码图像
- 设置验证码过期时间
Canvas绘制验证码
使用Canvas可以创建更复杂的验证码:

function drawCaptcha() {
const canvas = document.getElementById('captchaCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
const captcha = generateCaptcha();
ctx.font = '30px Arial';
ctx.fillStyle = '#000';
ctx.fillText(captcha, 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();
}
return captcha;
}
注意事项
- 前端验证不能替代服务器端验证
- 复杂验证码应考虑无障碍访问需求
- 定期更新验证码生成算法防止被破解
- 对于重要操作,建议使用更安全的验证方式如短信验证码
以上方法提供了基本的验证码实现,可根据具体需求进行调整和扩展。






