vue+element 数字加字母验证码(直接复制,简单易懂)

9 篇文章 0 订阅

 可直接复制代码!!!

<template>
  <div class="join_formitem">
    <el-form ref="form" :rules="rule" :model="form">
      <el-form-item label="验证码" prop="picLyanzhengma">
        <el-input
          type="text"
          placeholder="请输入验证码"
          v-model="form.picLyanzhengma"
        ></el-input>
      </el-form-item>
    </el-form>
    <div class="captcha">
      <input
        type="button"
        @click="createCode"
        class="verification"
        v-model="checkCode"
      />
    </div>
  </div>
</template>

 给表单加上校验,可用于判断输入的验证码是否正确

data() {
    return {
      form: {
        picLyanzhengma: "",
      },
      checkCode: "",
      code: "",
      rule: {
        picLyanzhengma: [
          { require: true, message: "验证码不能为空", trigger: "blur" },
          {
            validator: this.checkNumber,
            trigger: "blur",
          },
        ],
      },
    };
  },
checkNumber(rule, value, callback) {
      if (value == "") {
        callback(new Error("验证码不能为空!"));
      } else {
        if (value != this.checkCode) {
          callback(new Error("验证码错误!请注意大小写!"));
        } else {
          callback();
        }
      }
    },

定义验证码函数,每次点击更换验证码时都要调用

createCode() {
      //先清空验证码的输入
      this.code = "";
      this.checkCode = "";
      this.picLyanzhengma = "";
      //验证码的长度
      var codeLength = 4;
      //随机数
      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"
      );
      for (var i = 0; i < codeLength; i++) {
        //取得随机数的索引(0~35)
        var index = Math.floor(Math.random() * 36);
        //根据索引取得随机数加到code上
        this.code += random[index];
      }
      //把code值赋给验证码
      this.checkCode = this.code;
    },

最后就是简单的css排版 :

<style lang="less">
.join_formitem {
  display: flex;
  flex-direction: row;
  .el-form-item {
    display: flex;
    flex-direction: row;
  }
  .captcha {
    text-align: justify;
    .verification {
      border-radius: 12px;
      width: 100px;
      outline: none;
      letter-spacing: 5px;
      margin-left: 20px;
      height: 40px;
      transform: translateY(0px);
    }
  }
}
</style>

 最后显示出来的效果就是这样

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值