uniapp 表单验证

阐述:

  • 在业务需求的时候,有些是必填的字段,这时候我们如果使用普通的验证显然太麻烦了。此时uniapp提供了一套验证的规则。
验证代码如下:
  • 注意:这里form表单是必须的。
<template>
	<view>
		<form @submit="_formSubmit">
			<view class="content">
				<view>
					<image class="backimg" src="/static/images/image/background.png" />
				</view>
				<view class="content-input content-picker">
					<image class="iphone" src="/static/images/image/login/iPhone.png"></image>
					<picker class="sel-identity" :range="identityObj" @change="selectIdentity" :value="identityIndex" range-key="name">
						<view class="sel-identity-content">选择身份:{{identityObj[identityIndex].name}}</view>
					</picker>
				</view>
				<view class="content-input">
					<image class="iphone" src="/static/images/image/login/iPhone.png"></image>
					<input type="text" value="" v-model="iponeCode" name="phone" placeholder-class="placeholderStyle" placeholder="请输入手机号码" />
				</view>
				<view class="content-input">
					<image class="iphone" src="/static/images/image/login/pass.png"></image>
					<input type="text" value="" placeholder-class="placeholderStyle" placeholder="请输入密码" />
				</view>
				<view class="content-input-1">
					<view class="content-input-code">
						<image class="iphone" src="/static/images/image/login/pass.png"></image>
						<input name="Password" type="text" placeholder-class="placeholderStyle" value="" placeholder="请输入验证码" />
					</view>
					<button class="code-btn g-login-btn" @click="_getCode" :disabled="disabled">{{time}}</button>
				</view>
				<view class="login">
					<button class="login-btn g-login-btn" form-type="submit">立即登录</button>
				</view>
			</view>
		</form>
	</view>
</template>

验证代码如下:

const graceChecker = require('common/graceChecker.js') // 这个js需要创建 Hello uni-app(见图1)模板就有了。
<script>
	export default {
		_formSubmit(e) {
			console.log('form发生了submit事件,携带数据为:' + JSON.stringify(e.detail.value))
			// 进行表单检查
			let data = e.detail.value
			const loginRule = [
				{
					name:"phone",
					checkType: "string",
					checkRule:"1,100",
					errorMsg: "手机号不能为空"
				},
				{
					name:"phone",
					checkType: "phoneno",
					errorMsg: "手机号格式不正确"
				},
				{
					name:"Password",
					checkType: "string",
					checkRule: "1,100",
					errorMsg:"密码为必填项"
				}
			]
			let checkRes = graceChecker.check(data, loginRule)
			if(checkRes) {
			// 验证通过业务
			}else {
			 // 验证失败业务
			}
		}
</script>

表单使用注意:

  1. “checkType” 是 graceChecker.js 的规则,可以看下源码。比如想要验证手机号checkType:phoneno。

图1:
在这里插入图片描述

最终验证效果如下图:

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐