700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > tp6 微信小程序手机号验证码登录

tp6 微信小程序手机号验证码登录

时间:2020-09-29 22:59:09

相关推荐

tp6 微信小程序手机号验证码登录

logini.wxml

<!--pages/login/login.wxml--><view class="container"><view class="title">登录</view><form bindsubmit="formSubmit" ><view class="inputView"><input class="inputText" placeholder="请输入手机号" bindblur="phone" name="phone" /></view><view class="inputView"><input class="inputText" placeholder="请输入验证码" name="code" /><button class="line" disabled="{{disabled}}" size="mini" bindtap="sendcode">{{codebtn}}</button></view><view class="loginBtnView"><button class="loginBtn" type="primary" formType="submit">登录</button></view></form></view>

login.wxss

/* pages/login/login.wxss */.container { display: flex; flex-direction: column; padding: 0; } .inputView { line-height: 45px; border-bottom:1px solid #999999;} .title{width: 80%;font-weight: bold;font-size: 30px;}.inputText { display: inline-block; line-height: 45px; padding-left: 10px; margin-top: 11px;color: #cccccc; font-size: 14px;} .line {border: 1px solid #ccc;border-radius: 20px; float: right; margin-top: 9px;color: #cccccc;} .loginBtn { margin-top: 40px; border-radius:10px;}

login.js

// pages/login/login.jsimport WxValidate from '../../utils/WxValidate'//引入缓存类import Cache from '../../utils/Cache'const app = getApp()Page({/*** 页面的初始数据*/data: {codebtn:'发送验证码',disabled:false,phone:'',code:''},formSubmit(e){const params = e.detail.value;//console.log(params);if(!this.WxValidate.checkForm(params)){const error = this.WxValidate.errorList[0]//console.log(error);wx.showToast({title: error.msg,icon:'error',duration:2000})return false}wx.request({url: '/wxaizufang/login',data:{phone:params.phone,code:params.code},method:"GET",success:res=>{console.log(res);if(res.data.error_code == 500){wx.showToast({title: res.data.msg,icon:'error',duration:2000})}if(res.data.error_code == 0){wx.showToast({title:res.data.msg,duration:2000,success:function(res){wx.redirectTo({url: '/pages/add/add',})}})}}})},//发送短信验证码sendcode(e){const phone = this.data.phonewx.request({url: '/wxaizufang/code?',method:"POST",header:{token:Cache.get('token')},data:{phone:phone},success:res=>{const code = res.dataif(res.data.error_code == 999){wx.showToast({title:'手机号不能为空',icon:'error'})}if(res.data.error_code == 0){wx.showToast({title:res.data.msg,duration:2000})}this.setData({code:code})}})},showModal(error) {wx.showModal({content: error.msg,showCancel: false,})},/*** 生命周期函数--监听页面加载*/onLoad: function (options) {this.initValidate()},//获取输入的手机号phone(e){const phone = e.detail.valuethis.setData({phone:phone})},//验证函数initValidate() {const rules = {phone: {required:true,tel:true},code:{required: true,minlength:4}}const messages = {phone: {required:'请填写手机号',tel:'手机号错误!'},code:{required:'验证码不能为空',minlength:'验证码错误!'}}this.WxValidate = new WxValidate(rules, messages)},})

另外在utils中加了两个js文件

Cache,js

// 缓存类class Cache {// 构造方法 单位秒constructor({ expire = 3600 }) {// 成员属性 过期时间// 毫秒this.expire = new Date().getTime() + expire * 1000;}// 设置set(key, value) {let data = { expire: this.expire, value };// 设置缓存wx.setStorageSync(key, data);}// 永久forever(key, value) {let expire = new Date().getTime() + 9999999999 * 1000;let data = { expire, value };// 设置缓存wx.setStorageSync(key, data);}// 判断是否存在缓存has(key) {// 获取当前时间let time = new Date().getTime();// 缓存数据let data = wx.getStorageSync(key);if (data != '') {if (time > data.expire) { // 缓存过期// 删除过期缓存wx.removeStorageSync(key);return false;}return true;}return false;}// 获取get(key) {if (this.has(key)) {return wx.getStorageSync(key).value;}return null;}// 删除del(key) {wx.removeStorageSync(key);}}// 导出 有效期1小时export default new Cache({ expire: 3600 });

WxValidate.js

/*** 表单验证* * @param {Object} rules 验证字段的规则* @param {Object} messages 验证字段的提示信息* */class WxValidate {constructor(rules = {}, messages = {}) {Object.assign(this, {data: {},rules,messages,})this.__init()}/*** __init*/__init() {this.__initMethods()this.__initDefaults()this.__initData()}/*** 初始化数据*/__initData() {this.form = {}this.errorList = []}/*** 初始化默认提示信息*/__initDefaults() {this.defaults = {messages: {required: '这是必填字段。',email: '请输入有效的电子邮件地址。',tel: '请输入11位的手机号码。',url: '请输入有效的网址。',date: '请输入有效的日期。',dateISO: '请输入有效的日期(ISO),例如:-06-23,1998/01/22。',number: '请输入有效的数字。',digits: '只能输入数字。',idcard: '请输入18位的有效身份证。',equalTo: this.formatTpl('输入值必须和 {0} 相同。'),contains: this.formatTpl('输入值必须包含 {0}。'),minlength: this.formatTpl('最少要输入 {0} 个字符。'),maxlength: this.formatTpl('最多可以输入 {0} 个字符。'),rangelength: this.formatTpl('请输入长度在 {0} 到 {1} 之间的字符。'),min: this.formatTpl('请输入不小于 {0} 的数值。'),max: this.formatTpl('请输入不大于 {0} 的数值。'),range: this.formatTpl('请输入范围在 {0} 到 {1} 之间的数值。'),}}}/*** 初始化默认验证方法*/__initMethods() {const that = thisthat.methods = {/*** 验证必填元素*/required(value, param) {if (!that.depend(param)) {return 'dependency-mismatch'} else if (typeof value === 'number') {value = value.toString()} else if (typeof value === 'boolean') {return !0}return value.length > 0},/*** 验证电子邮箱格式*/email(value) {return that.optional(value) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(value)},/*** 验证手机格式*/tel(value) {return that.optional(value) || /^1[34578]\d{9}$/.test(value)},/*** 验证URL格式*/url(value) {return that.optional(value) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(value)},/*** 验证日期格式*/date(value) {return that.optional(value) || !/Invalid|NaN/.test(new Date(value).toString())},/*** 验证ISO类型的日期格式*/dateISO(value) {return that.optional(value) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(value)},/*** 验证十进制数字*/number(value) {return that.optional(value) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(value)},/*** 验证整数*/digits(value) {return that.optional(value) || /^\d+$/.test(value)},/*** 验证身份证号码*/idcard(value) {return that.optional(value) || /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)},/*** 验证两个输入框的内容是否相同*/equalTo(value, param) {return that.optional(value) || value === that.data[param]},/*** 验证是否包含某个值*/contains(value, param) {return that.optional(value) || value.indexOf(param) >= 0},/*** 验证最小长度*/minlength(value, param) {return that.optional(value) || value.length >= param},/*** 验证最大长度*/maxlength(value, param) {return that.optional(value) || value.length <= param},/*** 验证一个长度范围[min, max]*/rangelength(value, param) {return that.optional(value) || (value.length >= param[0] && value.length <= param[1])},/*** 验证最小值*/min(value, param) {return that.optional(value) || value >= param},/*** 验证最大值*/max(value, param) {return that.optional(value) || value <= param},/*** 验证一个值范围[min, max]*/range(value, param) {return that.optional(value) || (value >= param[0] && value <= param[1])},}}/*** 添加自定义验证方法* @param {String} name 方法名* @param {Function} method 函数体,接收两个参数(value, param),value表示元素的值,param表示参数* @param {String} message 提示信息*/addMethod(name, method, message) {this.methods[name] = methodthis.defaults.messages[name] = message !== undefined ? message : this.defaults.messages[name]}/*** 判断验证方法是否存在*/isValidMethod(value) {let methods = []for (let method in this.methods) {if (method && typeof this.methods[method] === 'function') {methods.push(method)}}return methods.indexOf(value) !== -1}/*** 格式化提示信息模板*/formatTpl(source, params) {const that = thisif (arguments.length === 1) {return function() {let args = Array.from(arguments)args.unshift(source)return that.formatTpl.apply(this, args)}}if (params === undefined) {return source}if (arguments.length > 2 && params.constructor !== Array) {params = Array.from(arguments).slice(1)}if (params.constructor !== Array) {params = [params]}params.forEach(function(n, i) {source = source.replace(new RegExp("\\{" + i + "\\}", "g"), function() {return n})})return source}/*** 判断规则依赖是否存在*/depend(param) {switch (typeof param) {case 'boolean':param = parambreakcase 'string':param = !!param.lengthbreakcase 'function':param = param()default:param = !0}return param}/*** 判断输入值是否为空*/optional(value) {return !this.methods.required(value) && 'dependency-mismatch'}/*** 获取自定义字段的提示信息* @param {String} param 字段名* @param {Object} rule 规则*/customMessage(param, rule) {const params = this.messages[param]const isObject = typeof params === 'object'if (params && isObject) return params[rule.method]}/*** 获取某个指定字段的提示信息* @param {String} param 字段名* @param {Object} rule 规则*/defaultMessage(param, rule) {let message = this.customMessage(param, rule) || this.defaults.messages[rule.method]let type = typeof messageif (type === 'undefined') {message = `Warning: No message defined for ${rule.method}.`} else if (type === 'function') {message = message.call(this, rule.parameters)}return message}/*** 缓存错误信息* @param {String} param 字段名* @param {Object} rule 规则* @param {String} value 元素的值*/formatTplAndAdd(param, rule, value) {let msg = this.defaultMessage(param, rule)this.errorList.push({param: param,msg: msg,value: value,})}/*** 验证某个指定字段的规则* @param {String} param 字段名* @param {Object} rules 规则* @param {Object} data 需要验证的数据对象*/checkParam(param, rules, data) {// 缓存数据对象this.data = data// 缓存字段对应的值const value = data[param] !== null && data[param] !== undefined ? data[param] : ''// 遍历某个指定字段的所有规则,依次验证规则,否则缓存错误信息for (let method in rules) {// 判断验证方法是否存在if (this.isValidMethod(method)) {// 缓存规则的属性及值const rule = {method: method,parameters: rules[method]}// 调用验证方法const result = this.methods[method](value, rule.parameters)// 若result返回值为dependency-mismatch,则说明该字段的值为空或非必填字段if (result === 'dependency-mismatch') {continue}this.setValue(param, method, result, value)// 判断是否通过验证,否则缓存错误信息,跳出循环if (!result) {this.formatTplAndAdd(param, rule, value)break}}}}/*** 设置字段的默认验证值* @param {String} param 字段名*/setView(param) {this.form[param] = {$name: param,$valid: true,$invalid: false,$error: {},$success: {},$viewValue: ``,}}/*** 设置字段的验证值* @param {String} param 字段名* @param {String} method 字段的方法* @param {Boolean} result 是否通过验证* @param {String} value 字段的值*/setValue(param, method, result, value) {const params = this.form[param]params.$valid = resultparams.$invalid = !resultparams.$error[method] = !resultparams.$success[method] = resultparams.$viewValue = value}/*** 验证所有字段的规则,返回验证是否通过* @param {Object} data 需要验证数据对象*/checkForm(data) {this.__initData()for (let param in this.rules) {this.setView(param)this.checkParam(param, this.rules[param], data)}return this.valid()}/*** 返回验证是否通过*/valid() {return this.size() === 0}/*** 返回错误信息的个数*/size() {return this.errorList.length}/*** 返回所有错误信息*/validationErrors() {return this.errorList}}export default WxValidate

后台代码

<?phpdeclare (strict_types = 1);namespace app\api\controller;use think\facade\Cache;class Phone{public function index(){//接收参数$data = input();//验证集$validate = Validate::rule(['phone'=>'require|mobile','code'=>'require|length:4']);//调用validate 里的check 验证方法if (!$validate->check($data)) {return Response::create(['error_code' => 500, 'msg' => $validate->getError(), 'data' => ''], 'json');}$code = Cache::get($data['phone']);//判断缓存if ($data['code'] != $code){return Response::create(['error_code' => 500, 'msg' => '验证码错误', 'data' => ''], 'json');}return Response::create(['error_code'=>0,'msg'=>'登录成功!','data'=>''],'json');}// 获取验证码public function getCode(){$data = input();$statusStr = array("0" => "短信发送成功","-1" => "参数不全","-2" => "服务器空间不支持,请确认支持curl或者fsocket,联系您的空间商解决或者更换空间!","30" => "密码错误","40" => "账号不存在","41" => "余额不足","42" => "帐户已过期","43" => "IP地址限制","50" => "内容含有敏感词");$code = rand(1000,9999);$smsapi = "/";$user = "1048551941"; //短信平台帐号$pass = md5("1048551941"); //短信平台密码$content="1901A:您的短信验证码为$code,请不要告诉其他人";//要发送的短信内容$phone = $data['0'];$sendurl = $smsapi."sms?u=".$user."&p=".$pass."&m=".$phone."&c=".urlencode($content);$result =file_get_contents($sendurl) ;// return json($result);if ($result == 0) {Cache::set($phone.$code,$code);return json(['error_code'=>0,'data'=>$code,'msg'=>'发送验证码成功']);}else{return json(['error_code'=>999,'data'=>$result,'msg'=>'网络异常 稍后重试']);}}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。