原生JS实现随机生成指定位数的验证码并校验

来源:互联网 发布:出售淘宝买家信息 编辑:程序博客网 时间:2024/05/16 02:52

功能:1.生成随机指定位数的验证码,生成的验证码字符可以是字母或数字
2. 忽略字母大小写比较验证码是否输入正确

一、求字母和数字的Unicode 编码

用str.charCodeAt();来求解:

0~9: 48-57
A-Z: 65-90
a-z: 97-122

二、利用Math.random()求随机数

str.formCharCode()从字符编码创建一个字符串

校验时统一转化为大写或者小写,这样子验证时可以忽略验证码的大小写

三、效果图


四、代码实现

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="text" placeholder="输入验证码" id="input">
<input type="text" id="gen" placeholder="生成的验证码"><button id="btnGen">生成验证码</button>
<button id="btnValidate">验证</button>
<script>


function genCode (len) {
if (typeof len === "undefined") // 默认验证码长度为4
len = 4;
// 生成 48 ~ 122 之间的随机整数
// 0 ~ 74
var validateCode = "";


while (validateCode.length < len) {
var rand = Math.floor(Math.random() * 75) + 48;
// console.log(rand);
// 判断是否在数字、大/小写字符范围内
if (rand >= 48 && rand <= 57
|| rand >= 65 && rand <= 90
|| rand >= 97 && rand <= 122) {
validateCode += String.fromCharCode(rand);
}
}


return validateCode;
}

document.getElementById("btnGen").onclick = function(){
document.getElementById("gen").value = genCode(6);
}


document.getElementById("btnValidate").onclick = function(){
var _input = document.getElementById("input").value,
_gen = document.getElementById("gen").value;
// 忽略大小写状态比较
// 都统一转换为大写后再比较
if (_input.toUpperCase() === _gen.toUpperCase()) {
alert("验证码正确");
} else {
alert("验证码输入有误");
}
}
</script>
</body>
</html>