分享給大家一段js生成驗證碼並驗證的代碼
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>JS生成驗證碼</title> <style type="text/css"> .code { background-image: url(code.jpg); font-family: Arial; font-style: italic; color: Red; border: 0; padding: 2px 3px; letter-spacing: 3px; font-weight: bolder; } .unchanged { border: 0; } </style> <script language="javascript" type="text/javascript"> var code; //在全局 定義驗證碼 function createCode() { code = ""; var codeLength = 6;//驗證碼的長度 var checkCode = document.getElementById("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]; } //alert(code); if (checkCode) { checkCode.className = "code"; checkCode.value = code; } } function validate() { var inputCode = document.getElementById("input1").value; if (inputCode.length <= 0) { alert("請輸入驗證碼!"); } else if (inputCode != code) { alert("驗證碼輸入錯誤!"); createCode();//刷新驗證碼 } else { alert("^-^ OK"); } } </script> </head> <body onload="createCode()"> <form action="#"> <input type="text" id="input1" /> <input type="text" onclick="createCode()" readonly="readonly" id="checkCode" class="unchanged" style="width: 80px" /><br /> <input id="Button1" onclick="validate();" type="button" value="確定" /> </form> </body> </html>眾所周知,js是客戶端的,那麼把驗證都做在客戶端有意義嗎?還是必須從服務器生成的驗證碼安全啊?前端生成的驗證碼安全嗎?
驗證碼是動態的,但要由客戶端識別,並返回正確數值才能正常驗證。這是一個流程問題,如果js的,那就是在客戶端處驗證,基本等於沒有一樣!!!最好是服務器生成,客戶端驗證,服務器確認,正常浏覽。這樣一個流程就萬無一失