当前位置:首页 > JavaScript

js 实现验证码

2026-02-28 22:27:03JavaScript

实现验证码的基本思路

验证码通常用于防止自动化脚本提交表单或进行恶意操作。在JavaScript中,可以通过生成随机字符或数字,并将其显示在页面上,同时与用户输入进行比对来实现验证码功能。

生成随机验证码

使用JavaScript生成包含数字和字母的随机字符串作为验证码。可以通过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;
}

显示验证码

将生成的验证码显示在HTML页面上,通常使用Canvas或普通的文本元素来呈现验证码。

<div id="captchaDisplay"></div>
function displayCaptcha() {
    const captcha = generateCaptcha();
    document.getElementById('captchaDisplay').textContent = captcha;
    return captcha; // 返回验证码用于后续验证
}

验证用户输入

用户提交表单时,需要比对用户输入的验证码与生成的验证码是否一致。

<input type="text" id="userCaptcha" placeholder="输入验证码">
<button onclick="validateCaptcha()">验证</button>
let currentCaptcha = displayCaptcha(); // 初始化验证码

function validateCaptcha() {
    const userInput = document.getElementById('userCaptcha').value;
    if (userInput === currentCaptcha) {
        alert('验证码正确');
    } else {
        alert('验证码错误,请重新输入');
        currentCaptcha = displayCaptcha(); // 刷新验证码
    }
}

增加验证码的复杂度

为了提高安全性,可以使用Canvas绘制带有干扰线或扭曲效果的验证码。

function drawCaptcha(captcha) {
    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(captcha, 10, 30);

    // 绘制干扰线
    ctx.strokeStyle = '#888';
    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();
    }
}

完整示例

以下是一个完整的HTML和JavaScript实现示例:

js 实现验证码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>验证码示例</title>
    <style>
        #captchaCanvas {
            border: 1px solid #000;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <canvas id="captchaCanvas" width="200" height="50"></canvas>
    <input type="text" id="userCaptcha" placeholder="输入验证码">
    <button onclick="validateCaptcha()">验证</button>
    <button onclick="refreshCaptcha()">刷新验证码</button>

    <script>
        let currentCaptcha;

        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 drawCaptcha(captcha) {
            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(captcha, 10, 30);

            ctx.strokeStyle = '#888';
            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();
            }
        }

        function refreshCaptcha() {
            currentCaptcha = generateCaptcha();
            drawCaptcha(currentCaptcha);
        }

        function validateCaptcha() {
            const userInput = document.getElementById('userCaptcha').value;
            if (userInput === currentCaptcha) {
                alert('验证码正确');
            } else {
                alert('验证码错误,请重新输入');
                refreshCaptcha();
            }
        }

        // 初始化
        refreshCaptcha();
    </script>
</body>
</html>

注意事项

  • 前端验证码仅能提供基本防护,无法完全阻止恶意攻击。对于高安全性需求,建议结合后端验证。
  • 避免使用过于简单的验证码(如纯数字),容易被破解。
  • 可以结合服务器端生成验证码并存储,以提高安全性。

标签: 验证码js
分享给朋友:

相关文章

js实现跳转

js实现跳转

使用 window.location 跳转 通过修改 window.location.href 实现页面跳转,这是最常用的方法。 window.location.href = 'https://…

php实现验证码

php实现验证码

PHP实现验证码的方法 使用GD库生成验证码 GD库是PHP中处理图像的扩展,可用于生成验证码图片。 <?php session_start(); $width = 120; $height…

js实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现dh

js实现dh

JavaScript 实现 DH(Diffie-Hellman)密钥交换 Diffie-Hellman(DH)密钥交换是一种安全协议,允许双方在不安全的通信信道上建立一个共享密钥。以下是如何在 Jav…

js手势实现

js手势实现

手势识别实现方法 在JavaScript中实现手势识别通常涉及监听触摸事件(touchstart、touchmove、touchend)或鼠标事件(mousedown、mousemove、mouseu…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…