卖坚果的怪叔叔 卖坚果的怪叔叔
  • 首页
  • 闲言碎语
  • 技术
  • 生活
  • 记录
  • 朋友
  • 热点新闻
  • 常用代码
  • 工具箱
  • 关于
首页 › 技术 › JS生成随机验证码校验(前端)

JS生成随机验证码校验(前端)

坚果大叔
2020-11-12 19:02:27技术阅读 2,656

HTML

<div class="box">
    <div class="code" id="checkCode">{{nowCode}}</div>
    <a href="###" @click="changeCode">看不清,换一张</a>
    <input type="text" placeholder="请输入验证码" v-model="inputCode">
    <button id="subBtn" @click="isLegalCode">验证</button>
</div>

CSS

.box {
    width:300px;
    height:150px;
    border:1px solid;
    margin:30px auto;
    position:relative;
}
.code {
    width:120px;
    height:40px;
    background-color:#D6E3BC;
    border:2px solid;
    text-align:center;
    font-size:24px;
    line-height:40px;
    position:absolute;
    top:20px;
    left:20px;
    letter-spacing:3px;
}
a {
    position:absolute;
    left:160px;
    top:30px;
    color:green;
}
input {
    width:180px;
    height:20px;
    top:90px;
    left:20px;
    position:absolute;
}
button {
    width:50px;
    height:26px;
    position:absolute;
    top:90px;
    right:26px;
    background-color:green;
    color:#fff;
    border:1px solid gray;
}

JS

// 生成验证码
createCode () {
    let codeLength = 6; // 验证码长度
    let codeChars = 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',
        '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++) {
        let charIndex = Math.floor(Math.random() * 52); // 随机产生0-52之间的整数
        this.nowCode += codeChars[charIndex]; 
    }
},
// 切换验证码
changeCode() {
    this.createCode();
},
// 校验验证码
isLegalCode() {
    if (this.inputCode == this.nowCode) {
        alert("验证码正确!");
    } else {
        alert("验证码不正确,请重试!");
    }
}
验证码
赞赏 赞(0)
本文系作者 @坚果大叔 原创发布在 卖坚果的怪叔叔。未经许可,禁止转载。
那些简单实用让你眼前一亮的鼠标滑过样式!
上一篇
晨曦
下一篇
在小程序中查看
搜你想看的
聚合文章
Nuxt3中的水合是什么?以及使用中的一些总结!
JS foo()
我生病😷
生活不易
闲言碎语
Memos
Nuxt3中的水合是什么?以及使用中的一些总结!
2025-08-30 19:42:35
1,159 0 0
Element Plus Upload 添加支持拖拽排序~
2025-07-30 20:55:55
844 1 0
Nuxt3中piana持久化处理!
2025-06-22 18:45:45
913 0 2
npm install 出现 Error:EISDIR:illegal operation on a directory 的错误提示!
2025-03-31 19:02:11
1,487 0 1
  • 0
博主

一位佛系的前端开发者,略通摄影,乐于尝试新事物,热衷于美食。

友链
故事胶片
公众号
坚果大叔 执行上下文 卖坚果的怪叔叔 Dacking
Copyright © 2017-2025 卖坚果的怪叔叔

开往-友链接力

萌ICP备20230818号

苏ICP备18048410号-3
  • 首页
  • 闲言碎语
  • 技术
  • 生活
  • 记录
  • 朋友
  • 热点新闻
  • 常用代码
  • 工具箱
  • 关于
# CSS # # JavaScript # # vue # # 微信 # # 生活 #
坚果大叔
327
文章
138
评论
399
喜欢