0
点赞
收藏
分享

微信扫一扫

原生js实现随机验证码校验

zhoulujun 2022-02-27 阅读 44

代码:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>随机验证码校验</title>
    <style>
      #code {
        width: 100px;
        height: 100px;
        background-color: #ddd;
        padding: 10px;
        line-height: 100px;
        /* 字体居中 */
        text-align: center;
        font-size: 20px;
        color: red;
        /* 字体加粗 */
        font-weight: bold;
      }
      input {
        /* 去除轮廓 */
        outline: none;
      }
    </style>
  </head>
  <body>
    <!-- 验证码 -->
    <div id="code"></div>
    <!-- 输入框、按钮 -->
    <input type="text" name="" id="newCode" />
    <input type="button" name="" id="validate" value="验证" />
    <script>
      // 页面加载时便执行
      window.onload = function () {
        // 全局变量,用于与用户输入的验证码进行比对
        var code;
        // 1.获取对应的标签
        var codeDiv = document.getElementById("code");
        var newCodeInput = document.getElementById("newCode");
        var validateBtn = document.getElementById("validate");
        createCode();

        // 获取min到max之间的整数(1-100)
        function random(max, min) {
          return Math.floor(Math.random() * (max - min) + min);
        }
        // 创建随机字符串,即随机生成验证码
        function createCode() {
          // 设置默认的空的字符串
          code = "";
          // 设置长度
          var codeLength = 4;
          var randomCode = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D',
            'E','F','G','H','I','J','K','L','M','N','O','P',
            'Q','R','S','T','U','V','W','X','Y','Z'];
          // 生成四个随机验证码
          for (var i = 0; i < codeLength; i++) {
            // 设置随机范围 0~36: 26个字母、10个阿拉伯数字
            var index = random(0, 36);
            code += randomCode[index];
          }
          codeDiv.innerHTML = code;
        }

        // 验证码校验
        validateBtn.onclick = function() {
            // 获取用户输入的验证码
            var newCode = newCodeInput.value.toUpperCase(); // 转成大写
            if (newCode === code) {
                // 校验成功,页面跳转到csdn
                window.location.href = "https://www.csdn.net/";
            } else {
                // 验证失败,提示用户
                alert("验证码不正确,请重新输入!");
                // 清空用户输入并重新生成验证码
                newCodeInput.value = '';
                createCode();
            }
            
        }
      };
    </script>
  </body>
</html>

效果:

 

举报

相关推荐

0 条评论