简单验证码倒计时,手机号正则校验

效果展示:

代码展示:

data: {
    //设置初始的状态、包含字体、颜色、还有等待事件
    tel: "",
    code: "",
    sendTime: '获取验证码',
    sendColor: '#363636',
    snsMsgWait: 60,
  }

 onLoad(){
    this.debounce = this.debounce()
  },
  debounce(){
    var timeOut = null;
    return () => {
      clearTimeout(timeOut);
      timeOut = setTimeout(() => {
        this.sendCode();
      }, 300);
    }
  },
  toast: (msg) => {
    wx.showToast({
      title: msg,
      icon: 'none',
      duration: 2000,
      mask: true
    })
  },
  sendCode(){
    if (this.data.tel != "") {
      // 60秒后重新获取验证码
      var inter = setInterval(function () {
        this.setData({
          smsFlag: true,
          sendColor: '#cccccc',
          sendTime: this.data.snsMsgWait + 's后重发',
          snsMsgWait: this.data.snsMsgWait - 1
        });
        if (this.data.snsMsgWait < 0) {
          clearInterval(inter)
          this.setData({
            sendColor: '#363636',
            sendTime: '获取验证码',
            snsMsgWait: 60,
            smsFlag: false
          });
        }
      }.bind(this), 1000);

      //发起请求
      codeApi({ phone: this.data.tel }).then(res => {
        if (!res.resultStatus) {
          return
        } else {
          this.toast("验证码发送成功!")
        }
      })
    } else {
      this.toast("请输入手机号")
      return
    }
  },
  //获取手机号
  handleGettel(e) {
    this.setData({
      tel: e.detail.value
    })
  },
  //获取验证码
  handleGetcode(e) {
    this.setData({
      code: e.detail.value
    })
  },
  //点击登录
  handleLogin() {
    if (this.data.tel == "") {
      this.toast('请输入手机号');
      return;
    }
    //使用正则校验手机号格式
    if (!(/^1[3|4|5|8][0-9]\d{8}$/.test(this.data.tel))) {
      this.toast('手机号输入错误');
      return;
    }
      
    if (this.data.code == "") {
      this.toast("验证码不可为空");
      return;
    }
    //调用api校验
    phoneLogin({
      phone: this.data.tel,
      code: this.data.code
    }).then(res => {
      console.log(res)
      if(res.resultStatus === false){
        this.toast("验证码输入错误");
      }else{
        //将用户登录状态缓存
        wx.setStorageSync('userInfo', res.resultData)
        const { accessToken } = wx.getStorageSync('userInfo')
        wx.setStorageSync('accessToken', accessToken)
        this.toast("登录成功")
        wx.navigateBack({
          delta: 2
        })
      }
        //成功登陆
       
    }).catch(err=>{
      console.log(err)
    })
  }
posted @ 2020-06-01 16:34  hello蔚蓝  阅读(136)  评论(0)    收藏  举报