在用户登陆时,为了防止恶意登陆、注册,因此我们需要在登陆/注册界面加上验证码。本篇,我们实现的时简单的验证码制作
js:在js上写一个简单的函数,用random()函数产生验证码。
1、将数字1-9,字符a-z的大小写都存放到数组中。
2、利用random()方法,产生随机数。
3、生成的随机数赋值到结果code上面(4为验证码)
4、将code放到前台页面上
5、获取用户输入的验证码,然后与code比较,如果不相等,则提示验证码输入错误。
具体代码如下:
//产生验证码
function createCode() {
code = "";
var codeLength = 4;
var selectChar = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
for (var i = 0; i < codeLength; i++) {
var charIndex = Math.floor(Math.random() * 60);
code += selectChar[charIndex];
}
if (code.length != codeLength) {
createCode();
}
return code;
}
//验证登陆
function check(){
if(codeText.value === code ){
return true;
}else {
alert("验证码输入错误!");
return false;
}
}
html
<input type="text" id="codeText" class="input input-big" name="code" placeholder="填写右侧的验证码" />
<span id = "codeTextArea" class="passcode" ></span>
效果图:
验证失败