萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 純數字驗證碼生成與驗證完整實例

完整 HTML 實現

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>數字驗證碼演示</title>
  <style>
    .captcha { 
      font-family: Arial, monospace; font-style: italic; font-weight: bold; 
      color: #c00; letter-spacing: 4px; border: 1px solid #ccc; 
      padding: 4px 8px; background: #f9f9f9; cursor: pointer; user-select: none;
    }
    .input-box { padding: 6px 10px; font-size: 16px; }
  </style>
</head>
<body onload="generateCaptcha()">
  <input type="text" id="userInput" class="input-box" placeholder="輸入驗證碼" />
  <input type="text" id="captchaBox" class="captcha" readonly onclick="generateCaptcha()" title="點擊刷新" />
  <br><br>
  <button onclick="validateCaptcha()">驗證</button>

  <script>
  var captchaCode = ''; // 全局存儲

  function generateCaptcha(len = 4) {
    var chars = '0123456789';
    captchaCode = '';
    for (var i = 0; i < len; i++) {
      captchaCode += chars[Math.floor(Math.random() * chars.length)];
    }
    var box = document.getElementById('captchaBox');
    box.value = captchaCode;
    // 可選:添加干擾線/背景圖片增強安全性
  }

  function validateCaptcha() {
    var input = document.getElementById('userInput').value.trim();
    if (!input) {
      alert('請輸入驗證碼!');
      return;
    }
    if (input !== captchaCode) {
      alert('驗證碼錯誤!');
      generateCaptcha(); // 刷新
    } else {
      alert('驗證通過!');
    }
  }
  </script>
</body>
</html>

安全性增強建議

  1. 服務端驗證為主:前端驗證只能攔截誤輸,防不住繞過。必須在後端再次校驗。
  2. 增加干擾:Canvas 繪製干擾線、噪點、扭曲字符。
  3. 字符集擴展:加入字母(區分大小寫)、排除易混淆字符(0/O, 1/l/I)。
  4. 限制嘗試次數:失敗 N 次鎖定或要求圖形驗證。
  5. 無障礙支持:提供語音驗證碼按鈕。

Canvas 版本核心片段

function drawCaptcha(canvas, code) {
  var ctx = canvas.getContext('2d');
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = '#f0f0f0';
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 干擾線
  for (var 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.strokeStyle = 'rgba(0,0,0,0.1)';
    ctx.stroke();
  }
  
  // 文字
  ctx.font = 'bold 24px Arial';
  ctx.fillStyle = '#c00';
  ctx.textBaseline = 'middle';
  for (var j = 0; j < code.length; j++) {
    var x = 20 + j * 30 + Math.random() * 5;
    var y = canvas.height / 2 + (Math.random() - 0.5) * 10;
    ctx.fillText(code[j], x, y);
  }
}
copyright © 萬盛學電腦網 all rights reserved