WeChat applet to determine whether the mobile phone number is legal example code

WeChat applet to determine whether the mobile phone number is legal example code

Scenario

Enter your mobile phone number on the registration page and check whether the entered mobile phone number is legal before requesting the registration interface;

Effect

Code

Import vant-weapp component: user-register.json

{
  "usingComponents": {
  	"van-cell-group": "@vant/weapp/cell-group/index",
  	"van-field": "@vant/weapp/field/index",
  	"van-dropdown-menu": "@vant/weapp/dropdown-menu/index",
  	"van-dropdown-item": "@vant/weapp/dropdown-item/index",
  	"van-button": "@vant/weapp/button/index"
  }
}

Write the layout file: user-register.wxml

<!-- pages/user-register/user-register.wxml -->
<view class="register-block">
  <view class="title">
    <text class="text">Register</text>
  </view>
  <van-cell-group class="input">
    <van-field label="学号" value="{{ studentNumber }}" placeholder="Please enter the student number" required clearable center bind:blur="setStudentNumber" />
    <van-field label="Username" value="{{ userName }}" placeholder="Please enter your username" required clearable center bind:blur="setUsername" />
    <van-field label="Class" value="{{ className }}" placeholder="Please enter your class" required clearable center bind:blur="setClassName" />
    <van-field label="Phone Number" value="{{ phoneNumber }}" placeholder="Please enter your phone number" error="{{ phoneLength || phoneFormat }}" error-message="{{ phoneError }}" required clearable center bind:blur="setphoneNumber" />
    <van-field label="Gender" required use-input-slot>
      <view style="position: absolute; left: -16rpx;" slot="input">
        <van-dropdown-menu active-color="#92B6D5">
          <van-dropdown-item value="{{ gender }}" options="{{ option1 }}" bind:change="changeGender" />
        </van-dropdown-menu>
      </view>
    </van-field>
    <van-field label="Campus" required use-input-slot>
      <view style="position: absolute; left: -16rpx;" slot="input">
        <van-dropdown-menu active-color="#92B6D5">
          <van-dropdown-item value="{{ area }}" options="{{ option2 }}" bind:change="changeArea" />
        </van-dropdown-menu>
      </view>
    </van-field>
    <van-field label="Password" value="{{ password }}" placeholder="Please enter your password" required clearable center type="password" bind:blur="setPassword" />
    <van-field label="Confirm password" value="{{ repassword }}" placeholder="Please enter your password again" error="{{ rePwdEqual }}" error-message="{{ errorMsg }}" required clearable center type="password" bind:blur="setRePassword" />
  </van-cell-group>
  <view class="login-block">
    <text class="text" bind:tap="gotoLogin">Log in now</text>
    <!-- <text class="">Forgot password</text> -->
  </view>
  <van-button class="btn" size="large" type="info" bind:tap="userRegister">Register</van-button>
</view>

Write style file: user-register.scss

/* pages/user-register/user-register.scss */
.register-block{
  margin: 200rpx 20rpx 0 20rpx;

  .title{
    text-align: center;
    margin-bottom: 60rpx;

    .text{
      font-size: 60rpx;
      font-weight: 300;
    }
  }

  .login-block{
    text-align: right;
    margin: 10rpx 0;

    .text{
      color: gray;
      font-weight: 300;
      font-size: smaller;
    }
  }
}

Determine whether the mobile phone number is legal

  /**
   * Enter your phone number*/
  setphoneNumber: function (event) {
    // console.log('username', event.detail.value)
    this.setData({
      phoneNumber: event.detail.value
    })
    const regex = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/
    if (this.data.phoneNumber.length !== 0 && this.data.phoneNumber.length !== 11) {
      this.setData({
        phoneLength: true,
        phoneError: 'The phone length is incorrect'
      })
    } else if (this.data.phoneNumber.length !== 0 && !regex .test(this.data.phoneNumber)) {
      this.setData({
        phoneFormat: true,
        phoneError: 'The phone number is incorrect'
      })
    }
  },

Complete js file: user-register.js

// pages/user-login/user-login.js

Page({
  /**
   * Initial data of the page */
  data: {
    studentNumber: '',
    userName: '',
    className: '',
    phoneNumber: '',
    mygender: '',
    schoolarea: '',
    password: '',
    repassword: '',
    gender: 0,
    option1: [
      { text: 'Please select your gender', value: 0 },
      { text: 'Male', value: 1 },
      { text: 'Female', value: 2 }
    ],
    area: 0,
    option2: [
      { text: 'Please select your campus', value: 0 },
      { text: 'North Campus', value: 1 },
      { text: 'South Campus', value: 2 }
    ],
    // Error message rePwdEqual: false,
    phoneLength: false,
    phoneFormat: false
  },

  /**
   * Enter your student ID*/
  setStudentNumber: function (event) {
    // console.log('username', event.detail.value)
    this.setData({
      studentNumber: event.detail.value
    })
  },

  /**
   * Enter your username */
  setUsername: function (event) {
    // console.log('username', event.detail.value)
    this.setData({
      userName: event.detail.value
    })
  },

  /**
   * Enter your class */
  setClassName: function (event) {
    // console.log('username', event.detail.value)
    this.setData({
      className: event.detail.value
    })
  },

  /**
   * Enter your phone number*/
  setphoneNumber: function (event) {
    // console.log('username', event.detail.value)
    this.setData({
      phoneNumber: event.detail.value
    })
    const myReg = /^(((13[0-9{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1})) + \d{8})$/
    if (this.data.phoneNumber.length !== 0 && this.data.phoneNumber.length !== 11) {
      this.setData({
        phoneLength: true,
        phoneError: 'The phone length is incorrect'
      })
    } else if (this.data.phoneNumber.length !== 0 && !myReg.test(this.data.phoneNumber)) {
      this.setData({
        phoneFormat: true,
        phoneError: 'The phone number is incorrect'
      })
    }
  },

  /**
   * Modify gender* @param {*} event
   */
  changeGender: function (event) {
    if (event.detail === 1) {
      this.setData({
        mygender: 'Male'
      })
    } else if (event.detail === 2) {
      this.setData({
        mygender: 'female'
      })
    } else if (event.detail === 0) {
      wx.showToast({
        title: 'Please select gender', // prompt content duration: 2000, // delay time mask: true // display transparent mask to prevent touch penetration})
    }
    console.log('Change gender', event.detail + this.data.mygender)
  },

  /**
   * Change the campus */
  changeArea: function (event) {
    if (event.detail === 1) {
      this.setData({
        schoolarea: 'North Campus'
      })
    } else if (event.detail === 2) {
      this.setData({
        schoolarea: 'South Campus'
      })
    } else if (event.detail === 0) {
      wx.showToast({
        title: 'Please select your campus', // prompt content duration: 2000, // delay time mask: true // display transparent mask to prevent touch penetration})
    }
    console.log('Change campus', event.detail + this.data.schoolarea)
  },

  /**
   * Enter password */
  setPassword: function (event) {
    // console.log('password', event.detail.value)
    this.setData({
      password: event.detail.value
    })
  },

  /**
   * Re-enter password */
  setRePassword: function (event) {
    // console.log('repassword', event.detail.value)
    this.setData({
      repassword: event.detail.value
    })
    if (this.data.password === this.data.repassword && this.data.password.length !== 0) {
      this.setData({
        rePwdEqual: false,
        errorMsg: ''
      })
    } else if (this.data.password !== this.data.repassword && this.data.password.length !== 0) {
      this.setData({
        rePwdEqual: true,
        errorMsg: 'The two passwords you entered do not match'
      })
    }
  },

  /**
   * Enter the login interface */
  gotoLogin: function () {
    // Currently we want to jump to another interface, but keep the existing interface wx.redirectTo({
      url: '../user-login/user-login'
    })
  },

  /**
   * Request registration */
  userRegister: function () {
    // console.log('studentNumber', this.data.studentNumber)
    // console.log('userName', this.data.userName)
    // console.log('className', this.data.className)
    // console.log('phoneNumber', this.data.phoneNumber)
    // console.log('mygender', this.data.mygender)
    // console.log('schoolarea', this.data.schoolarea)
    const existStudentNumber = this.data.studentNumber.length !== 0
    const existUserName = this.data.userName.length !== 0
    const existClassName = this.data.className.length !== 0
    const existPhoneNumber = this.data.phoneNumber.length !== 0
    const existGender = this.data.mygender.length !== 0
    const existArea = this.data.schoolarea.length !== 0
    // console.log('studentNumber', existStudentNumber)
    // console.log('userName', existUserName)
    // console.log('className', existClassName)
    // console.log('phoneNumber', existPhoneNumber)
    // console.log('mygender', existGender)
    // console.log('schoolarea', existArea)
    if (existStudentNumber && existUserName && existClassName && existPhoneNumber && existGender && existArea && !this.data.rePwdEqual && !this.data.phoneLength && !this.data.phoneFormat) {
      if (this.data.password === this.data.repassword && this.data.password !== '') {
        // Initiate network request wx.request({
          url: 'http://api/user/register',
          method: 'post',
          data: {
            student_number: this.data.studentNumber,
            class_name: this.data.className,
            name: this.data.userName,
            phone_number: this.data.phoneNumber,
            gender: this.data.mygender,
            area: this.data.schoolarea,
            password: this.data.password,
            second_password: this.data.repassword
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success(res) {
            console.log(res)
            if (res.data.code === 200) {
              wx.showToast({
                title: 'Registration successful! ',
                icon: 'success'
              })
              wx.redirectTo({
                url: '/pages/user-login/user-login'
              })
            } else {
              wx.showToast({
                title: 'Registration failed! ',
                icon: 'none'
              })
              console.log('Registration failed!')
              console.log(res)
            }
          },
          fail(msg) {
            console.log(msg)
          }
        })
      }
    } else if (!existStudentNumber) {
      wx.showToast({
        title: 'Student ID cannot be empty! ',
        icon: 'none'
      })
    } else if (!existUserName) {
      wx.showToast({
        title: 'Username cannot be empty! ',
        icon: 'none'
      })
    } else if (!existClassName) {
      wx.showToast({
        title: 'Class cannot be empty! ',
        icon: 'none'
      })
    } else if (!existPhoneNumber) {
      wx.showToast({
        title: 'Mobile number cannot be empty! ',
        icon: 'none'
      })
    } else if (!existGender) {
      wx.showToast({
        title: 'Please select your gender! ',
        icon: 'none'
      })
    } else if (!existArea) {
      wx.showToast({
        title: 'Please select your campus! ',
        icon: 'none'
      })
    } else {
      wx.showToast({
        Title: 'Please enter relevant information as prompted! ',
        icon: 'none'
      })
    }
  },

  /**
   * Life cycle function--listen for page loading*/
  onLoad: function (options) {

  },

  /**
   * Life cycle function - listen for the completion of the initial rendering of the page*/
  onReady: function () {

  },

  /**
   * Life cycle function--monitor page display*/
  onShow: function () {

  },

  /**
   * Life cycle function--listen for page hiding*/
  onHide: function () {

  },

  /**
   * Life cycle function--monitor page uninstallation*/
  onUnload: function () {

  },

  /**
   * Page related event processing function - listen to user pull-down action */
  onPullDownRefresh: function () {

  },

  /**
   * The function that handles the bottoming event on the page*/
  onReachBottom: function () {

  },

  /**
   * User clicks on the upper right corner to share*/
  onShareAppMessage: function () {

  }
})

Summarize

This is the end of this article about how WeChat mini program determines whether a mobile phone number is legal. For more information about how WeChat mini program determines whether a mobile phone number is legal, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • WeChat applet to determine the implementation code of the mobile phone number

<<:  How to install MySql in CentOS 8 and allow remote connections

>>:  Use of Linux tr command

Recommend

Vue implements image dragging and sorting

This article example shares the specific code of ...

How to modify the initial password of MySQL on MAC

Problem description: I bought a Mac and installed...

Sample code on how to implement page caching in vue mobile project

background On mobile devices, caching between pag...

Let's talk about destructuring in JS ES6

Overview es6 adds a new way to get specified elem...

Detailed explanation of MySQL binlog usage

binlog is a binary log file that records all DML ...

Detailed explanation of fuser command usage in Linux

describe: fuser can show which program is current...

Steps to configure nginx ssl to implement https access (suitable for novices)

Preface After deploying the server, I visited my ...

CSS uses radial-gradient to implement coupon styles

This article will introduce how to use radial-gra...

MySQL index principle and usage example analysis

This article uses examples to illustrate the prin...

Docker cleanup environment operation

Start cleaning carefully! List unused volumes doc...

Solve the abnormal error when building vue environment with webpack

Table of contents First, configure package.json T...

Tomcat Nginx Redis session sharing process diagram

1. Preparation Middleware: Tomcat, Redis, Nginx J...

Example usage of Linux compression file command zip

The ".zip" format is used to compress f...