JS Realizes Random Verification Code Function
- 2021-07-21 06:55:57
- OfStack
1. Verification code verification is a verification point that often appears on web pages. There are many types of verification codes. The following code only realizes a simple verification function.
<div>
<input type = "text" id = "input" value="" />
<input type = "button" id="code" onclick="createCode()"/>
<input type = "button" value = " Validation " onclick = "validate()"/>
</div>
2. Add some styles casually
#code{
font-family:Arial;
font-style:italic;
font-weight:bold;
border:0;
letter-spacing:2px;
color:blue;
}
3. JS, in which I have added detailed remarks
// Settings 1 A global variable, which is convenient to save the verification code
var code;
function createCode(){
// Default first code Is an empty string
code = '';
// Set the length, look at the demand here, and I set it here 4
var codeLength = 4;
var codeV = document.getElementById('code');
// Set random characters
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');
// Cycle codeLength I set it up 4 Is the loop 4 Times
for(var i = 0; i < codeLength; i++){
// Set the range of random numbers , This is set to 0 ~ 36
var index = Math.floor(Math.random()*36);
// String splicing Will each random character Carry out splicing
code += random[index];
}
// Assign the spliced string to the displayed Value
codeV.value = code;
}
// The following is to judge whether or not == No need to explain the code of
function validate(){
var oValue = document.getElementById('input').value.toUpperCase();
if(oValue ==0){
alert(' Please enter the verification code ');
}else if(oValue != code){
alert(' The verification code is incorrect, please re-enter it ');
oValue = ' ';
createCode();
}else{
window.open('http://www.baidu.com','_self');
}
}
// The reason for setting this place is that every time you enter the interface display, 1 Random verification code, blank if not set
window.onload = function (){
createCode();
}
Special reference of js verification code: https://www.ofstack.com/Special/922. htm