表单校验、发送验证码、本地校验验证码是否正确、表单提交——uniapp+uview组件

1.HTML

<u--form labelPosition="left" :model="model1" ref="form1">
					<u-form-item label="卡号" prop="cardNo" labelWidth="80" borderBottom>
						<u--input v-model="model1.cardNo" border="none" placeholder="请填写绑定卡号"></u--input>
						<!-- <u-button slot="right" @tap="getCode" :text="tips" type="primary" size="mini"
							:disabled="disabled1"></u-button> -->
					</u-form-item>
					<u-form-item label="手机号" prop="mobile" labelWidth="80" borderBottom>
						<u--input v-model="model1.mobile" border="none" placeholder="请填写手机号"></u--input>
						<!-- <u-button slot="right" @tap="getCode" :text="tips" type="primary" size="mini"
							:disabled="disabled1"></u-button> -->
						<view class="getCode" :class="{activeCode:codeFlag}" @click="getCode">
							{{codeTxt}}
						</view>
					</u-form-item>
					<u-form-item label="验证码" prop="code" labelWidth="80" borderBottom ref="item1">
						<u--input v-model="model1.code" border="none" placeholder="请填写验证码"></u--input>
					</u-form-item>
				</u--form>
				<u-button type="primary" text="绑定" customStyle="margin-top: 50px" @click="submit"
					shape="circle"></u-button>

2.Script

data() {
			return {
				disabled1: false,
				tips: '',
				model1: {
					// cardNo: '57100677366', //卡号
					cardNo: '', //卡号
					mobile: '', //手机号
					code: ''
				},
				rules: {
					cardNo: [{
						type: 'string',
						required: true,
						message: '请填写绑定卡号',
						trigger: ['blur', 'change']
					}],
					mobile: [{
						type: 'string',
						required: true,
						message: '请填写手机号',
						trigger: ['blur', 'change']
					}],
					code: {
						type: 'string',
						required: true,
						message: '请填写验证码',
						trigger: ['blur', 'change']
					}
				},
				openid: '',
				verificationCode: '',
				codeTxt: '获取验证码',
				codeFlag: true, // 控制按钮是否可点击
			}
		},
		// 一定要设置,否则校验不生效
		onReady() {
			// 如果需要兼容微信小程序,并且校验规则中含有方法等,只能通过setRules方法设置规则
			this.$refs.form1.setRules(this.rules)
		},
// 发送验证码
			getCode() {
				let that = this
				if (this.codeFlag == false) {
					return
				}
				if (that.model1.cardNo == '') {
					uni.$u.toast('卡号不能为空');
				} else if (that.model1.mobile == '') {
					uni.$u.toast('手机号码不能为空');
				} else {
					uni.showToast({
						title: '验证码发送成功',
						icon: 'none',
						duration: 2000
					})
					this.codeFlag = false;
					var time = 60
					this.codeTxt = time + 'S' + '重新获取'

					var timer = setInterval(() => {
						this.codeTxt = '获取验证码'
						if (time == 1) {
							this.codeFlag = true;
							clearInterval(timer)
						} else {
							time--
							this.codeTxt = time + 'S' + '重新获取'
						}

					}, 1000)
					// 发布接口,注意post请求携带参数的方式,这里将对象重新赋值
					setTimeout(() => {
						that.model1 = {
							cardNo: that.model1.cardNo,
							mobile: that.model1.mobile
						}
						uni.showLoading({
							title: '加载中...',
							mask: true
						});
						uni.request({
							// header: {
							// 	'Content-Type': 'application/x-www-form-urlencoded'
							// },
							url: 'http://wx.cunkou.co/api/wx/sendSms', //仅为示例,并非真实接口地址。
							method: 'POST',
							data: {
								cardNo: that.model1.cardNo,
								mobile: that.model1.mobile
							},
							// dataType: 'json',
							success: (res) => {
								uni.hideLoading();
								if (res.data.code == 0) {
									that.verificationCode = res.data.data
								} else {
									uni.showToast({
										title: res.data.message,
										icon: 'none',
										duration: 2000
									})
								}

							}

						});
					}, 2000)

				}

			},
// 表单提交
			submit() {
				let that = this
				// 如果有错误,会在catch中返回报错信息数组,校验通过则在then中返回true
				this.$refs.form1.validate().then(res => {

					uni.showModal({
						content: '你确定要绑定吗?',
						success: function(res) {

							if (res.confirm) {
								if (that.model1.code !== that.verificationCode) {
									uni.$u.toast('验证码不正确');
								} else {
									that.model1 = {
										cardNo: that.model1.cardNo,
										mobile: that.model1.mobile,
										code: that.model1.code,
										openid: that.openid
									}
									uni.showLoading({
										title: '加载中...',
										mask: true
									});
									uni.request({
										// header: {
										// 	'Content-Type': 'application/x-www-form-urlencoded'
										// },
										url: 'http://wx.cunkou.co/api/wx/bindCard', //为示例,并非真实接口地址。
										method: 'POST', //一定要大写
										data: {
											cardNo: that.model1.cardNo,
											mobile: that.model1.mobile,
											code: that.model1.code,
											openid: that.openid
										},
										// dataType: 'json',
										success: (res) => {
											uni.hideLoading();
											if (res.data.code == 0) {
												uni.showToast({
													title: '绑定成功',
													icon: 'none',
													duration: 2000
												})
												// uni.setStorage({
												// 	key:'userInfo',
												// 	data:res.data
												// })
												// uni.setStorageSync(KEY,DATA)
												uni.setStorageSync('userInfo', res.data
													.data);

												setTimeout(function() {
													uni.reLaunch({
														url: '/pages/mine/mine'
													})
												}, 2000);

											} else {
												uni.showToast({
													title: res.data.message,
													icon: 'none',
													duration: 2000
												})
											}

										}

									});
								}

							} else if (res.cancel) {}
						}
					});

				}).catch(errors => {
					uni.$u.toast('请填写完整的信息')
				})
			},

3.Style

<style lang="scss">
	.u-demo-block__content {
		margin: 20rpx;
	}

	.getCode {
		height: 60rpx;
		width: 180rpx;
		background: #f7f7f7;
		color: #666666;
		line-height: 60rpx;
		font-size: 24rpx;
		text-align: center;
		border-radius: 50rpx;
	}

	.getCode.activeCode {
		background: #2D99F5;
		color: #FFFFFF;
	}
</style>

### 解析 uView uni-app 表单验证规则失效解决方案 #### 设置表单校验规则 对于`u-view`中的表单组件,确保在页面加载完成后立即设置表单校验规则是非常重要的。这可以通过监听生命周期钩子函数`mounted()`来完成,在该阶段可以访问到已经挂载好的DOM元素以及组件实例。 ```javascript export default { data() { return { formData: {}, // 表单数据对象 rules: {} // 验证规则定义 } }, methods: {}, mounted() { this.$nextTick(() => { if (this.$refs.uForm) { this.$refs.uForm.setRules(this.rules); } }); } } ``` 上述代码片段展示了如何利用`$nextTick`等待视图更新完毕后再调用`setRules`方法[^2]。 #### 初始化赋值后的处理 当涉及到表单字段初始值设定的情况时,需要注意的是,如果是在创建组件之前就给这些字段赋予了特定值,则可能导致某些情况下校验逻辑未能正常工作。因此建议先清空原有值再重新绑定新的模型数据,并再次触发一次完整的渲染过程以确保所有状态同步一致。 ```html <u-form ref="uForm" :model="formData" :rules="rules"> <!-- form items --> </u-form> ``` ```javascript methods: { resetFormDataAndValidate() { Object.assign(this.formData, {}); setTimeout(() => { this.$forceUpdate(); this.validateForm(); }, 0); }, validateForm() { this.$refs.uForm.validate(valid => { console.log('validate result:', valid); }) } }, created() { // 假设这里获取到了服务器端返回的数据并希望将其作为表单默认值显示出来 const serverData = {}; Object.assign(this.formData, serverData); // 调用重置与验证的方法 this.resetFormDataAndValidate(); } ``` 这段JavaScript代码说明了怎样安全地初始化表单数据并且随后立刻执行一次手动验证操作[^3]。 #### 组件内部自定义事件响应 另外值得注意的一点是,有时候即使按照官方文档指导完成了相应配置仍然会碰到问题。此时不妨考虑是否存在其他因素干扰了正常的流程运转——比如是否有第三方插件修改过全局配置?或者是父级容器传递下来的props参数影响到了当前组件的行为表现? 为了排查此类潜在冲突,可以在组件内注册一些额外的日志记录语句用于监控关键节点的变化情况: ```javascript watch: { '$route'(to, from) { console.debug('[Route Change]', to.path); }, formData: { handler(newValue, oldValue){ console.info(`[Form Data Changed]\nNew Value:\n${JSON.stringify(newValue)}\nOld Value:\n${JSON.stringify(oldValue)}`); }, deep: true, } } ``` 以上措施有助于更清晰地了解整个应用运行期间的状态变迁轨迹,从而更快定位具体原因所在。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值