js編寫驗證碼以及驗證
<style>
#code{
font-family:Arial;
font-style:italic;
font-weight:bold;
border:0;
letter-spacing:2px;
color:blue;
}
</style>
<div>
<input type = "text" id = "input" value="" />
<input type = "button" id="code" onclick="createCode()"/>
<input type = "button" value = "驗證" onclick = "validate()"/>
</div>
<script>
//設置一個全局的變量,便於保存驗證碼
var code;
function createCode(){
//首先默認code為空字符串
code = ‘‘;
//設置長度,這裏看需求,我這裏設置了4
var codeLength = 4;
var codeV = 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‘);
//循環codeLength 我設置的4就是循環4次
for(var i = 0; i < codeLength; i++){
//設置隨機數範圍,這設置為0 ~ 36
var index = Math.floor(Math.random()*36);
//字符串拼接 將每次隨機的字符 進行拼接
code += random[index];
}
//將拼接好的字符串賦值給展示的Value
codeV.value = code;
}
//下面就是判斷是否== 的代碼,無需解釋
function validate(){
var oValue = document.getElementById(‘input‘).value.toUpperCase();
if(oValue ==0){
alert(‘請輸入驗證碼‘);
}else if(oValue != code){
alert(‘驗證碼不正確,請重新輸入‘);
oValue = ‘ ‘;
createCode();
}else{
alert(‘驗證碼正確‘);
}
}
//設置此處的原因是每次進入界面展示一個隨機的驗證碼,不設置則為空
window.onload = function (){
createCode();
}
</script>
js編寫驗證碼以及驗證