作者:n_light征蓝妙 | 来源:互联网 | 2023-07-24 19:42
uni-app获取短信验证码
1、输入手机号码
2、点击获取验证码
3、代码示例
<view ><view><inputv-model="userPwdPhone" type="text" maxlength="20" placeholder="请输入动态验证码" placeholder-style="font-size:30upx;"/></view><view @tap="getPhonecode">{{codeBtn.codeText}}</view>
</view>var codeBtn= {codeTime: 60,codeText: "获取验证码",codeStatus: true
};
var rules = {userName: {rule:/\S/,msg: "账号不能为空"},userNamePhone: {rule: /^1[3456789]\d{9}$/,msg: "手机号格式错误"},userPwdPhone: {rule: /^[0-9]{6}$/,msg: "请输入6位数字验证码"}
};
getPhonecode(){console.log(this.validate(&#39;userNamePhone&#39;) && this.codeBtn.codeStatus);if(this.validate(&#39;userNamePhone&#39;) && this.codeBtn.codeStatus) {this.getValidataCode();}
}
validate(key){let bool=true;if(!this.rules[key].rule.test(this[key])){uni.showToast({title:this.rules[key].msg,icon:&#39;none&#39;})bool=false;return false;}return bool;
}
getValidataCode() {let t = this;util.request(&#39;/mobile/user/getValidateCode&#39;,"GET",{userNamePhone:t.userNamePhone},function(res){if(res.status == &#39;0001&#39;){t.myCode = res.data;t.codeBtn.codeStatus = false;let timerId = setInterval(() => {let codetime = t.codeBtn.codeTime;codetime--;t.codeBtn.codeTime = codetime;t.codeBtn.codeText = codetime + "s";if(codetime < 1) {clearInterval(timerId)t.codeBtn.codeText = "重新获取";t.codeBtn.codeTime = 60;t.codeBtn.codeStatus = true;}},1000)}else if(res.status == &#39;0003&#39;){uni.showToast({title:&#39;验证码不正确!&#39;,icon:&#39;none&#39;})}});
}
效果图如下: