欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

微信小程序手机号码验证功能的实例代码

程序员文章站 2023-11-13 12:26:10
wxml

wxml

<form bindsubmit='formsubmit'>
 <view class='all'>
  <text>手机号:</text>
  <input name="phone" placeholder='请输入手机号' type='number' style='color:#333' placeholder-style="color:#666" maxlength="11" bindinput='blurphone'></input>
 </view>
 <button formtype="submit">保存</button>
</form>

wxss

.all {
 border-top: 1rpx solid #efefef;
 border-bottom: 1rpx solid #efefef;
 height: 98rpx;
 font-size: 28rpx;
 display: flex;
 align-items: center;
}
button {
 width: 480rpx;
 height: 80rpx;
 background-color: #7ecffd;
 font-size: 30rpx;
 color: #fff;
 border-radius: 8px;
 margin: 50rpx auto;
}

js

page({
 /**
  * 页面的初始数据
  */
 data: {
  ajxtrue: false,
 },
 // 手机号验证
 blurphone: function(e) {
  var phone = e.detail.value;
  let that = this
  if (!(/^1[34578]\d{9}$/.test(phone))) {
   this.setdata({
    ajxtrue: false
   })
   if (phone.length >= 11) {
    wx.showtoast({
     title: '手机号有误',
     icon: 'success',
     duration: 2000
    })
   }
  } else {
   this.setdata({
    ajxtrue: true
   })
   console.log('验证成功', that.data.ajxtrue)
  }
 },
 // 表单提交
 formsubmit(e) {
  let that = this
  let val = e.detail.value
  let ajxtrue = this.data.ajxtrue
  if (ajxtrue == true) {
   //表单提交进行
  } else {
   wx.showtoast({
    title: '手机号有误',
    icon: 'success',
    duration: 2000
   })
  }
 },
 /**
  * 生命周期函数--监听页面加载
  */
 onload: function(options) {
 },
 /**
  * 生命周期函数--监听页面初次渲染完成
  */
 onready: function() {
 },
 /**
  * 生命周期函数--监听页面显示
  */
 onshow: function() {
 },
 /**
  * 生命周期函数--监听页面隐藏
  */
 onhide: function() {
 },
 /**
  * 生命周期函数--监听页面卸载
  */
 onunload: function() {
 },
 /**
  * 页面相关事件处理函数--监听用户下拉动作
  */
 onpulldownrefresh: function() {
 },
 /**
  * 页面上拉触底事件的处理函数
  */
 onreachbottom: function() {
 },
 /**
  * 用户点击右上角分享
  */
 onshareappmessage: function() {
 }
})

下面看下微信小程序正则判断手机号的示例代码

var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
if (this.data.del.length == 0) {
 wx.showtoast({
  title: '输入的手机号为空',
  icon: 'success',
  duration: 1500
 })
 return false;
} else if (this.data.del.length < 11) {
 wx.showtoast({
  title: '手机号长度有误!',
  icon: 'success',
  duration: 1500
 })
 return false;
} else if (!myreg.test(this.data.del)) {
 wx.showtoast({
  title: '手机号有误!',
  icon: 'success',
  duration: 1500
 })
 return false;
} else {
 wx.showtoast({
  title: '填写正确',
  icon: 'success',
  duration: 1500
 })
}

总结

以上所述是小编给大家介绍的微信小程序手机号码验证功能的实例代码,希望对大家有所帮助