在移动开发的时候,通过手机号获取验证码进行账号注册或者修改密码等操作是非常常见的操作,不管是在iOS开发、Android开发、flutter开发或者是微信小程序开发,都是如此。那么本篇博文就来分享一下微信小程序开发的时候,实现通过手机号获取验证码的功能。
其实微信小程序实现上述功能也不算什么难的功能,无非就是手机号的校验,以及调用接收短信验证码接口等流程。本博文直接通过实例代码案例来直观展示功能实现,直接贴文件代码是为了方便新手直接使用,请根据实际情况选择性参考,多谢支持。具体实现如下所示:
1、register.js文件:
const app = getApp()
Page({
onLoad() {
wx.setNavigationBarTitle({
title: '身份验证'
})
},
data: {
phone: '',
phoneChange: true,
// 验证码是否正确
isCode: true,
phoneCode: '',
getText: '获取验证码',
},
onReady: function () {
this.navbarTap();
},
// 手机验证
getPhone: function (e) {
let phone = e.detail.value;
this.setData({ phone: phone })
if (!(/^1[34578]\d{9}$/.test(phone))) {
this.setData({
getPhone: false
})
if (phone.length >= 11) {
wx.showToast({
title: '手机号有误',
icon: 'none',
duration: 1000
})
}
} else {
this.setData({
getPhone: true
})
}
},
// 验证码输入
input: function (e) {
let that = this;
let value = e.detail.value;
let phoneCode = this.data.phoneCode;
that.setData({
value: value,
isCode: false,
})
if (value.length >= 4) {
if (value == phoneCode) {
that.setData({
isCode: true,
})
} else {
that.setData({
isCode: false,
})
wx.showModal({
content: '输入验证码有误',
showCancel: false,
success: function (res) { }
})
}
}
},
// 验证码按钮
codeBtn: function () {
let phoneChange = this.data.phoneChange;
let getPhone = this.data.getPhone;
let phone = this.data.phone;
let n = 59;
let that = this;
if (!getPhone) {
wx.showToast({
title: '手机号有误',
icon: 'success',
duration: 1000
})
} else {
if (phoneChange) {
this.setData({
phoneChange: false
})
let sendtime = setInterval(function () {
let str = '(' + n + ')' + '重新获取'
that.setData({
getText: str
})
if (n <= 0) {
that.setData({
phoneChange: true,
getText: '重新获取'
})
clearInterval(sendtime);
}
n--;
}, 1000);
//获取验证码接口写在这里
app.sendMsg(phone).then(res => {
console.log('请求获取验证码.res =>', res)
}).catch(err => {
console.log(err)
})
}
}
},
//表单提交
formSubmit(e) {
let val = e.detail.value
var phone = val.phone //电话
var code = val.code //验证码
},
})
2、register.json文件:
{
"usingComponents": {}
}
3、register.wxml文件:
4、register.wxss文件:
/* pages/register/register.wxss */
.content {
width: 100%;
height: auto;
padding: 0 50rpx;
box-sizing: border-box;
}
.phone-box {
width: 100%;
height: 89rpx;
border-bottom: 1rpx solid #efefef;
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
}
.phone {
color: #333;
margin-right: 60rpx;
font-size: 28rpx;
}
.number {
color: #333;
font-size: 28rpx;
width: 220rpx;
}
.getNum {
width:210rpx;
height:48rpx;
background:#F59A23;
border-radius:8rpx;
font-size:28rpx;
font-family:PingFang-SC-Medium;
color:rgba(255, 255, 255, 1);
line-height:48rpx;
/* margin-right:36rpx; */
margin-left: 60rpx;
text-align:center;
}
.submit {
width: 480rpx;
height: 80rpx;
background: #F59A23;
border-radius: 8rpx;
margin-top: 80rpx;
color: #fff;
font-size: 32rpx;
}
具体效果图如下所示:
以上就是本章全部内容,欢迎关注三掌柜的微信公众号“程序猿by三掌柜”,三掌柜的新浪微博“三掌柜666”,欢迎关注!
三掌柜的微信公众号:
三掌柜的新浪微博: