Vue implements mobile phone verification code login

Vue implements mobile phone verification code login

This article shares the specific code of Vue to implement mobile phone verification code login for your reference. The specific content is as follows

Verification Code

<template>
  <div>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="Mobile number" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="Please enter your phone number" size=""
                    maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="Verification code" prop="code">
          <el-row :span="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.code" auto-complete="off" placeholder="Please enter the verification code" size=""
                        maxlength="4"
                        @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-col>
            <el-col :span="12">
              <div class="login-code">
                <!--Verification code component-->
                <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
                           :disabled="getCodeBtnDisable">{{ codeBtnWord }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!--Sliding verification component-->
        <Verify></Verify>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">Login</el-button>
        </el-form-item>
      </el-form>

    </el-main>
  </div>
</template>

Vue verification tool class used

export default {
  // Limit the input to numbers only (two decimal places can be entered)
  limitInputPointNumber(val) {
    if (val === 0 || val === "0" || val === "" || val === undefined) {
      return "";
    } else {
      let value = null;
      value = val.replace(/[^\d.]/g, ""); // Clear all characters except "number" and "." value = value.replace(/\.{2,}/g, ​​"."); // Only keep the first one. Clear all the extra characters value = value
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
      value = value.replace(/^(-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // Only two decimals can be entered return value;
    }
  },

  handleRouteToArray(route) {
    const matches = route.path.split('/')
    matches.shift()
    let newMatch = []
    matches.map((item, i) => {
      if (matches[i - 1]) {
        item = newMatch[i - 1] + '/' + item
      }
      newMatch.push(item)
    })
    newMatch = newMatch.map(item => {
      return `/${item}`
    })
    return newMatch
  },

  // The password must be at least 8 characters long and must contain any 3 of uppercase, lowercase, numbers, and special symbols testPassWord: function (str) {
    var rC = {
      lW: '[az]',
      uW: '[AZ]',
      nW: '[0-9]',
      sW: '[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]'
    }
    function Reg (str, rStr) {
      var reg = new RegExp(rStr)
      if (reg.test(str)) return true
      else return false
    }
    if (str.length < 8) {
      return false
    } else {
      var tR = {
        l: Reg(str, rC.lW),
        u: Reg(str, rC.uW),
        n: Reg(str, rC.nW),
        s: Reg(str, rC.sW)
      }
      if ((tR.l && tR.u && tR.n) || (tR.l && tR.u && tR.s) || (tR.s && tR.u && tR.n) || (tR.s && tR.l && tR.n)) {
        // document.title = "The password meets the requirements"
        return true
      } else {
        return false
      }
    }
  },

  // Password verification 8-30 characters pwdReg: /^([0-9a-zA-Z]|(?:&)|(?:~)|(?:!)|(?:@)|(?:#)|(?:\$)|(?:%)|(?:\^)|(?:\*)){8,30}$/,

  // Phone number verification phoneReg: /^1[3|4|5|6|7|8][0-9]{9}$/,

  // Format money formatUSD (val, currency) {
    if (val === '' || val === '--' || val === undefined) {
      return '--'
    }
    // First determine whether the data has a decimal point let newVal = String(Number(val).toFixed(2))
    // Convert scientific notation to normal string display if (newVal.includes('e+')) {
      newVal = Number(newVal).toLocaleString()
      newVal = this.unFormatAmount(newVal)
    }
    let dotIdx = newVal.lastIndexOf('.')
    let dotVal = '.00' // Keep the data after the decimal point if (dotIdx >= 0) {
      dotVal = newVal.substr(dotIdx, newVal.length)
      newVal = newVal.slice(0, dotIdx)
    }

    let len ​​= newVal.length
    let arr = []
    let lastIndex = null
    while (len > 0) {
      lastIndex = len
      len -= 3
      arr.unshift(newVal.substring(len, lastIndex))
    }
    val = arr.join(',')

    if (currency) {
      newVal = `${currency} ${val}${dotVal}`
    } else {
      // newVal = `$ ${val}${dotVal}`
      newVal = `¥ ${val}${dotVal}` // Default is RMB}
    return newVal
  },

  // Format the amount, excluding decimal points, amount symbols, etc. Enter an integer formatAmount (val) {
    if (val === '' || val === '--' || val === undefined) {
      return '--'
    }
    if (val === 0 || val === '0') {
      return 0
    }
    // First determine whether the data has a decimal point let newVal = String(val)
    let dotIdx = newVal.lastIndexOf('.')
    let dotLength = 0
    if (newVal.split('.').length > 1) {
      dotLength = newVal.split('.')[1].length
    }
    let dotVal = '' // Keep the data after the decimal point if (dotIdx >= 0) {
      newVal = String(Number(val).toFixed(5))
      dotVal = newVal.substr(dotIdx, dotLength + 1)
      newVal = newVal.slice(0, dotIdx)
    }
    let len ​​= newVal.length
    let arr = []
    let lastIndex = null
    while (len > 0) {
      lastIndex = len
      len -= 3
      arr.unshift(newVal.substring(len, lastIndex))
    }
    val = arr.join(',')
    if (dotVal.length < 2) {
      dotVal = ''
    }
    return val + dotVal
  },

  // Determine whether the data is empty isEmptyVal (val) {
    if (val === undefined || val === '') {
      return '--'
    } else {
      return val
    }
  },

    // Format year, month, day type: Chinese display mode (ch) and splicing mode // Note: Chinese display mode is only required when passing parameters through the interface, otherwise it is American formatYMD (now, type='ch') {
    if (!now || now === 'null' || now === '--' || now === undefined) {
      return '--'
    }
    if (Number(now)) {
      now = new Date(now)
    }
    // Compatible with IE browser, YY-MM-DD format if (typeof now === 'string' && now.includes('-')) {
      now = this.NewDate(now)
    }
    if (now) {
      let year = ''
      let month = ''
      let date = ''
      // The 8 bits here are used to return a format like 20180423 if (String(now).length === 8 && String(now).indexOf('-') === -1 && String(now).indexOf('/') === -1) {
        const getNow = String(now)
        return `${getNow.substring(4, 6)}/${getNow.substring(6, 8)}/${getNow.substring(0, 4)}`
      } else {
        now = new Date(now)
        year = now.getFullYear()
        month = now.getMonth() + 1
        date = now.getDate()
      }
      if (month < 10) {
        month = `0${month}`
      }
      if (date < 10) {
        date = `0${date}`
      }
      if (type === 'ch') {
        return `${year}-${month}-${date}`
      } else if (type) {
        return `${year}${type}${month}${type}${date}`
      } else {
        return `${month}/${date}/${year}`
      }
    } else {
      return ''
    }
  },

  // Format time year, month, day, hour, minute, second formatDate (now, type) {
    if (!now || now === 'null' || now === '--' || now === undefined) {
      return '--'
    }
    if (now) {
      now = new Date(now)
      let year = now.getFullYear()
      let month = now.getMonth() + 1
      let date = now.getDate()
      let hour = now.getHours()
      let minute = now.getMinutes()
      let second = now.getSeconds()
      if (month < 10) {
        month = `0${month}`
      }
      if (date < 10) {
        date = `0${date}`
      }
      if (hour < 10) {
        hour = `0${hour}`
      }
      if (minute < 10) {
        minute = `0${minute}`
      }
      if (second < 10) {
        second = `0${second}`
      }
      if (type) {
        return `${month}/${date}/${year} ${hour}:${minute}:${second}`
      } else {
        return `${month}-${date}-${year}`
      }
    } else {
      return ''
    }
  },
}

Just put the complete one so it will be easier to read

<template>
  <div>
    <el-main>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="Mobile number" prop="phone">
          <el-input v-model="ruleForm.phone" placeholder="Please enter your phone number" size=""
                    maxlength="11"></el-input>
        </el-form-item>

        <el-form-item label="Verification code" prop="code">
          <el-row :span="24">
            <el-col :span="12">
              <el-input v-model="ruleForm.code" auto-complete="off" placeholder="Please enter the verification code" size=""
                        maxlength="4"
                        @keyup.enter.native="submitForm('ruleForm')"></el-input>
            </el-col>
            <el-col :span="12">
              <div class="login-code">
                <!--Verification code component-->
                <el-button @click="getCode()" :class="{'disabled-style':getCodeBtnDisable}"
                           :disabled="getCodeBtnDisable">{{ codeBtnWord }}
                </el-button>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <!--Sliding verification component-->
        <Verify></Verify>

        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">Login</el-button>
        </el-form-item>
      </el-form>

    </el-main>
  </div>
</template>

<script>
//Import tool class import Verify from "@/components/Verify";
import event from "../utils/event"
import common from "@/utils/common";

let params;
export default {
  name: "LoginIphone",
  components: {Verify},
  data() {
    //Use regular expression to verify the phone number const checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('Phone number cannot be empty'));
      } else {
        //Get the regular expression of the phone number in the tool class const reg = common.phoneReg
        // console.log(reg.test(value));
        if (reg.test(value)) {
          callback();
        } else {
          //If the validation input is wrong, clear this.ruleForm.phone = ''
          return callback(new Error('Please enter a correct phone number'));
        }
      }
    };

    return {
      ruleForm: {
        phone: '',
        code: '',
      },

      codeBtnWord: 'Get verification code', //Get verification code button text// waitTime: 61, //Get verification code button expiration time waitTime: 2, //Get verification code button expiration time// Verification rules: {
        phone:
          {validator: checkPhone, trigger: 'blur'}
        ],
        code: [
          {required: true, message: 'Please enter the verification password', trigger: 'blur'}
        ]
      }
    };
  },
  //Calculated properties computed
  computed: {
    // Control whether the get verification code button is clickable getCodeBtnDisable: {
      //Set button 61s
      // get() {
      // if (this.waitTime === 61) {
      // if (this.ruleForm.phone) {
      // return false
      // }
      // return true
      // }
      // return true
      // }
      get() {
        if (this.waitTime === 2) {
          if (this.ruleForm.phone) {
            return false
          }
          return true
        }
        return true
      },
      // Note: Because the calculated property itself does not have a set method, it does not support modification in the method. I will do this below, so I need to manually add set() {
      }
    },

  }, methods: {

    getCode() {
      const _this = this
      params = {}
      params.phone = this.ruleForm.phone
      // Call the SMS verification code interface_this.$axios.post('/sendMessage', params).then(res => {
        console.log("--------Check the value of the background response-----", res)
        //Store all data const mydata = res.data.data
        console.log("I am in the SMS interface -->", mydata)

        //Save verification code params.yz = mydata.vCode

        console.log("I am checking the verification code-------" + mydata.vCode)
        console.log("I am checking the number of calls-------" + mydata.count)

        if (res.data.code === 200) {
          this.$message({
            message: 'Verification code has been sent, please wait...',
            type: 'success',
            center: true
          })
        }
        if (res.data.data.count >= 5) {
          //Call the slider verification component event.$emit("VERIFY")
        }

      })

      // Because the timer is used below, you need to save this pointer let that = this
      that.waitTime--
      that.getCodeBtnDisable = true
      this.codeBtnWord = `Re-acquire after ${this.waitTime}s`
      let timer = setInterval(function () {
        if (that.waitTime > 1) {
          that.waitTime--
          that.codeBtnWord = `Retrieve after ${that.waitTime}s`
        } else {
          clearInterval(timer)
          that.codeBtnWord = 'Get verification code'
          that.getCodeBtnDisable = false
          // that.waitTime = 61
          that.waitTime = 2
        }
      }, 1000)
    },
    submitForm(formName) {
      const _this = this
      //Judge whether the verification code entered is empty if (this.ruleForm.code != null) {
        this.$refs[formName].validate((valid) => {
          if (valid) {

            _this.$axios.post("/iosLogin", {
              "phone": this.ruleForm.phone,
              "Verification": this.ruleForm.code
            }).then(res => {

              console.log(res.data)
            })


            // console.log("I am submitting:", par)
            //
            // const jwt = par.headers['authorization']
            // console.log("I am token->", jwt)
            // const userInfo = par.data.data
            // console.log("View user information=", userInfo)
            //
            // // Share the data // _this.$store.commit("SET_TOKEN", jwt)
            // _this.$store.commit("SET_USERINFO", userInfo)
            //
            // // Get // console.log("I got _this.$store.getters.getUser")
            // console.log(_this.$store.getters.getUser)

            // _this.$router.push("/blogs")

          } else {
            console.log('error submit!!');
            return false;
          }
        });
      } else {
        this.$message({
          showClose: true,
          message: 'Please enter an error',
          type: 'error'
        });
      }
    }

  }

}
</script>
<style scoped>
.el-button.disabled-style {
  background-color: #EEEEEE;
  color: #CCCCCC;
}

.demo-ruleForm {
  max-width: 500px;
  margin: 0 auto;
}
</style>

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Vue implementation of verification code login method example
  • Use vue to realize the registration page effect vue to realize SMS verification code login
  • Vue implements graphic verification code login
  • Vue implements mobile phone number and verification code login (60s countdown disabled)
  • Vue implements SMS verification code login function (process detailed explanation)
  • Vue implements sample code for sending SMS verification code login via mobile phone number

<<:  A brief analysis of the four import methods and priorities in CSS

>>:  Summary of considerations for writing web front-end code

Recommend

JavaScript Interview: How to implement array flattening method

Table of contents 1 What is array flattening? 2 A...

About the pitfall record of Vue3 transition animation

Table of contents background Problem location Fur...

VMware Tools installation and configuration tutorial for Ubuntu 18.04

This article records the installation and configu...

Ideas for creating wave effects with CSS

Previously, I introduced several ways to achieve ...

Summary of the differences between Vue's watch, computed, and methods

Table of contents 1 Introduction 2 Basic usage 2....

Summary of some common techniques in front-end development

1. How to display the date on the right in the art...

VUE implements timeline playback component

This article example shares the specific code of ...

VMware virtual machine three connection methods example analysis

NAT In this way, the virtual machine's networ...

CSS3 overflow property explained

1. Overflow Overflow is overflow (container). Whe...

Analysis of product status in interactive design that cannot be ignored in design

In the process of product design, designers always...

Analysis of the difference between emits and attrs in Vue3

Table of contents in conclusion Practice Analysis...

SQL uses ROW_NUMBER() OVER function to generate sequence number

Syntax: ROW_NUMBER() OVER(PARTITION BY COLUMN ORD...