工具类 - 生成图片验证码并验证

生成图片验证码并验证

 

一个简单的前端JS生成验证码并验证功能

 

<html>  
    <head>
        <title>验证码</title>  
        <style type="text/css">  
        #code
        {
            font-style:italic;
            font-weight:bold;
            border:0;
            letter-spacing:2px;
            color: #4567ff;
            background-color: #e4e4e4;
        }
        </style>
    </head>
    <body>
        <div>
        <form action="***" method='POST' id='loginForm'>
            <input type = "text" id = "inputCode"/>
            <input type = "button" id="code" onclick="createCode()"/>
            <button type="button" id="submitBtn">登录</button>
        </form>
        </div>
    </body>  
</html>

 

$(function(){
    createCode();
    var code;
    function createCode() {
        code = "";
        var codeLength = 4;
        var checkCode = document.getElementById("code");

        var random = new Array(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++) {
            var index = Math.floor(Math.random()*36);
            code += random[index];
        }
        checkCode.value = code;
    }

    $("#submitBtn").click(function () {
        var inputCode = $("#inputCode").val().toUpperCase();
        if(inputCode.length <= 0) {
            alert("请输入验证码");
        } else if(inputCode != code ) {
            alert("验证码输入错误");
            createCode();
            $("#inputCode").val("")
        } else {
            $("#loginForm").submit();
        }
    });
})
 

 

 

猜你喜欢

转载自hellolove.iteye.com/blog/2338762
今日推荐