使用JS來實現驗證碼功能

來源:互聯網
上載者:User

標籤:style   blog   class   code   java   ext   

        最近想為自己的Django部落格添加驗證碼功能,本來想使用第三方庫來實現的,不過考慮到添加第三方庫對效能的影響,以及第三方庫是否安全可靠的問題,還是用自己的代碼來實現吧。反正用JS來實現驗證碼功能又不是很難。

        簡單來說,用一個create_code()方法在頁面中產生驗證碼,然後control_submit()方法檢測驗證碼文字框(id=“user_input_code”)的鍵盤輸入事件,當文字框輸入了超過4個字元後,調用verify_code ()檢測輸入的字元與產生的驗證碼是否一致,

假如一致的話,把提交評論按鈕的disabled屬性從true改為false,假如不一致的話,在頁面顯示驗證碼錯誤。

       js代碼如下:

var code ;function create_code(){    //產生驗證碼    code = "";    var codeLength = 4;    var checkCode = $("#checkCode");    var selectChar = 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 charIndex = Math.floor(Math.random()*36);        code +=selectChar[charIndex];    }    if(checkCode){        checkCode.addClass("code");        checkCode.val(code);    }}function verify_code (){    //驗證驗證碼    var user_input_code = $("#user_input_code").val().toLowerCase().trim();    if(user_input_code.length <=0){        return false;    } else if(user_input_code != code.toLowerCase()){        return false;    }    return true;}function control_submit() {    //當驗證碼驗證成功後,才允許提交評論    $("#user_input_code").keyup(function () {        if ($("#user_input_code").val().trim().length>=4) {              if (verify_code()) {               $("#submit_comment").attr("disabled", false);           } else {               $("#valid_failed").text("驗證碼錯誤");           }        } else {             $("#valid_failed").text("");        }    });}

 

        在html頁面中對應的form中增加下面元素:

 <form ...>          <input id="user_input_code" type="text" name="code" placeholder="請輸入右側的驗證碼"/>      <input type="text" readonly="readonly" id="checkCode" class="code" style="width: 60px;" />      <p id="valid_faild"></p>      <tr>        <td colspan="2">        <input id="submit_comment" type="submit" disabled="true" name="submit" value="提交評論">        </td>      </tr></form>

 

      最後在css檔案中修改一下驗證碼元素的屬性,例如字元間隔,顏色,背景圖片等,即可完成驗證碼功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.