微信小程序实现注册、登录页面的小功能整理,希望对大家有帮助。
1. 正则验证手机号码
var
mobile = that.data.phone;
var
myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/;
if
(!myreg.test(mobile)) {
wx.showToast({
title:
'手机号有误!'
,
icon:
'success'
,
duration: 1500
})
return
;
}
wx.showToast({
title:
'手机号正确!'
,
icon:
'success'
,
duration: 1500
})
|
2. 60秒倒计时
发送短信验证码后会有60秒的倒计时功能。
网上有很多这种插件,很方便
比如: http://smsow.zhenzikj.com/doc/sdk.html
使用方法
1.引入插件countdown.js
var
CountDown = require(
'../../utils/countdown.js'
);
|
2.在 onLoad 周期初始化
onLoad:
function
() {
this
.countdown =
new
CountDown(
this
);
}
|
3. 在获取验证码的按钮上增加captchaDisabled、captchaTxt 分别用于控制倒计时过程中是否可以点击、倒计时秒数提示
<button class=
'codeBtn'
bindtap=
'getSmsCaptcha'
disabled=
'{{captchaDisabled}}'
>{{captchaTxt}}</button>
|
4. 调用start方法触发倒计时
getSmsCaptcha(e) {
this
.countdown.start();
}
|
3. 发送短信验证码
小编使用的是榛子云短信(http://smsow.zhenzikj.com/doc/sdk.html)的发送验证码短信。
目前提供了普通版和云函数版,建议下载云函数版的。两个版本中都提供了对验证码的支持,你无需生成验证码,SDK已经帮你都弄好了。
如何使用
1)配置域名
在微信公众平台-小程序管理中配置域名https://smsdeveloper.zhenzikj.com,如下图:
2) 引入sdk
var
zhenzisms = require(
'../../utils/zhenzisms.js'
);
|
3)初始化
zhenzisms.client.init(
'https://sms_developer.zhenzikj.com'
,
'你的榛子云appId'
,
'你的榛子云appSecret'
);
|
4) 发送验证码短信
zhenzisms.client.sendCode(
function
(res) {
wx.showToast({
title: res.data.data,
icon:
'none'
,
duration: 2000
})
}, that.data.phone,
'验证码为:{code}'
,
''
, 60 * 5, 4);
|
参数1:请求后的用于接收返回结果的回调函数
参数number:接收者手机号码
参数3:短信模板,其中{code}为验证码占位符,会自动替换
参数messageId:该条信息的唯一标识,可用于查询
参数seconds:验证码有效期,单位是秒
参数length:验证码长度,比如4位或6位
返回结果是json格式的字符串, code: 发送状态,0为成功。非0为发送失败,可从data中查看错误信息
当然,你也可以使用云函数版的,请参考文档: http://smsow.zhenzikj.com/doc/weixinmp_yun_sdk_doc2.html