uniapp的表单校验方式整理

uniapp的表单校验方式整理

这里我使用的模板为:
uniapp的表单校验方式整理_第1张图片

第一种:

uniapp本身自带表单校验的js文件,代码写的很简洁,也是比较全面的
uniapp的表单校验方式整理_第2张图片

只要按照规则校验即可,下面是对应的校验代码:

/**
数据验证(表单验证)
来自 grace.hcoder.net 
作者 hcoder 深海
*/
export default {
	error:'',
	check : function (data, rule){
		for(var i = 0; i < rule.length; i++){
			if (!rule[i].checkType){return true;}
			if (!rule[i].name) {return true;}
			if (!rule[i].errorMsg) {return true;}
			if (!data[rule[i].name]) {this.error = rule[i].errorMsg; return false;}
			switch (rule[i].checkType){
				case 'string':
					var reg = new RegExp('^.{' + rule[i].checkRule + '}$');
					if(!reg.test(data[rule[i].name])) {this.error = rule[i].errorMsg; return false;}
				break;
				case 'int':
					var reg = new RegExp('^(-[1-9]|[1-9])[0-9]{' + rule[i].checkRule + '}$');
					if(!reg.test(data[rule[i].name])) {this.error = rule[i].errorMsg; return false;}
					break;
				break;
				case 'between':
					if (!this.isNumber(data[rule[i].name])){
						this.error = rule[i].errorMsg;
						return false;
					}
					var minMax = rule[i].checkRule.split(',');
					minMax[0] = Number(minMax[0]);
					minMax[1] = Number(minMax[1]);
					if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
						this.error = rule[i].errorMsg;
						return false;
					}
				break;
				case 'betweenD':
					var reg = /^-?[1-9][0-9]?$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
					var minMax = rule[i].checkRule.split(',');
					minMax[0] = Number(minMax[0]);
					minMax[1] = Number(minMax[1]);
					if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
						this.error = rule[i].errorMsg;
						return false;
					}
				break;
				case 'betweenF': 
					var reg = /^-?[0-9][0-9]?.+[0-9]+$/;
					if (!reg.test(data[rule[i].name])){this.error = rule[i].errorMsg; return false;}
					var minMax = rule[i].checkRule.split(',');
					minMax[0] = Number(minMax[0]);
					minMax[1] = Number(minMax[1]);
					if (data[rule[i].name] > minMax[1] || data[rule[i].name] < minMax[0]) {
						this.error = rule[i].errorMsg;
						return false;
					}
				break;
				case 'same':
					if (data[rule[i].name] != rule[i].checkRule) { this.error = rule[i].errorMsg; return false;}
				break;
				case 'notsame':
					if (data[rule[i].name] == rule[i].checkRule) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'email':
					var reg = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'phoneno':
					var reg = /^1[0-9]{10,10}$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'zipcode':
					var reg = /^[0-9]{6}$/;
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'reg':
					var reg = new RegExp(rule[i].checkRule);
					if (!reg.test(data[rule[i].name])) { this.error = rule[i].errorMsg; return false; }
				break;
				case 'in':
					if(rule[i].checkRule.indexOf(data[rule[i].name]) == -1){
						this.error = rule[i].errorMsg; return false;
					}
				break;
				case 'notnull':
					if(data[rule[i].name] == null || data[rule[i].name].length < 1){this.error = rule[i].errorMsg; return false;}
				break;
			}
		}
		return true;
	},
	isNumber : function (checkVal){
		var reg = /^-?[1-9][0-9]?.?[0-9]*$/;
		return reg.test(checkVal);
	}
}

应用代码:

<template>
	<view>
		<page-head title="form"></page-head>
		<view class="uni-padding-wrap uni-common-mt">
			<form @submit="formSubmit" @reset="formReset">
				<view class="uni-form-item uni-column">
					<view class="title">姓名</view>
					<input class="uni-input" name="nickname" placeholder="请输入姓名" />
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">性别</view>
					<radio-group name="gender">
						<label>
							<radio value="男" /><text></text>
						</label>
						<label>
							<radio value="女" /><text></text>
						</label>
					</radio-group>
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">爱好</view>
					<checkbox-group name="loves">
						<label>
							<checkbox value="读书" /><text>读书</text>
						</label>
						<label>
							<checkbox value="写字" /><text>写字</text>
						</label>
					</checkbox-group>
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">年龄</view>
					<slider value="20" name="age" show-value></slider>
				</view>
				<view class="uni-form-item uni-column">
					<view class="title">保留选项</view>
					<view>
						<switch name="switch" />
					</view>
				</view>
				<view class="uni-btn-v">
					<button form-type="submit">Submit</button>
					<button type="default" form-type="reset">Reset</button>
				</view>
			</form>
		</view>
	</view>
</template>
<script>
	import graceChecker from "../../../common/graceChecker.js"
	export default {
		data() {
			return {
			}
		},
		methods: {
			formSubmit: function(e) {
				console.log('form发生了submit事件,携带数据为:' + JSON.stringify(e.detail.value))
                //定义表单规则
                var rule = [
                    {name:"nickname", checkType : "string", checkRule:"1,3",  errorMsg:"姓名应为1-3个字符"},
                    {name:"gender", checkType : "in", checkRule:"男,女",  errorMsg:"请选择性别"},
                    {name:"loves", checkType : "notnull", checkRule:"",  errorMsg:"请选择爱好"}
                ];
                //进行表单检查
                var formData = e.detail.value;
                var checkRes = graceChecker.check(formData, rule);
                if(checkRes){
                    uni.showToast({title:"验证通过!", icon:"none"});
                }else{
                    uni.showToast({ title: graceChecker.error, icon: "none" });
                }
			},
			formReset: function(e) {
				console.log('清空数据')
			}
		}
	}
</script>

<style>
	.uni-form-item .title {
		padding: 20rpx 0;
	}
</style>

第二种:

uni-forms也带表单的校验,相较于第一种的话,校验的种类就不是很全了,可以自己传入校验规则进行校验,提示样式更加鲜明,只能说各利弊了。

表单校验的核心代码:

uniapp的表单校验方式整理_第3张图片
代码比较多这里就不粘贴了。
没有找到手机号对应的校验方式,自己用的又比较多,所以手动在代码里面添加了
uniapp的表单校验方式整理_第4张图片
uniapp的表单校验方式整理_第5张图片
非常的便捷

也可以在使用的时候添加自己的校验方式:

uniapp的表单校验方式整理_第6张图片

最后附上完成的页面使用(只保留了核心代码,样式需要自行修改):

<template>
		<view class = "content">
			<view class = "content-in">
				<uni-forms ref="valiForm" :rules="rules" :model="valiFormData" >
					<view class = "login-t">
						<text class = "login-text">重置密码</text>
					</view>
					<view class = "login-i" >
						<uni-forms-item required name="phone" class = "imgList">
							 <uni-easyinput  style ="width:500rpx;" v-model="valiFormData.phone" focus placeholder="请输入您的手机号"/>
						</uni-forms-item>
					</view>
					
					<view class = "login-p" >
						<uni-forms-item  required name="password" class = "imgList">
							<uni-easyinput  v-model="valiFormData.password" type = 'password' placeholder="请输入您的密码" />
						</uni-forms-item>
						 
					</view>
					
					<view class = "login-p"  >
						<uni-forms-item  required name="repassword" class = "imgList">
							<uni-easyinput  v-model="valiFormData.repassword"  type = 'password' placeholder="请再次输入您的密码" />
						</uni-forms-item>
						
					</view>
					
					<view class = "login-i">
						<uni-forms-item required name="code" class = "imgList">
							<uni-easyinput  v-model="valiFormData.code" focus placeholder="请输入短信验证码" />
						</uni-forms-item>
						<!-- <text class="try" style="font-size:10rpx;" >获取验证码</text> -->
						<view class="try" style="font-size:24rpx;" @click.stop="getCode()">{{getCodeText}}</view>
					</view>
					<view class = "login-b">
						<button class= "btn" @click="submit('valiForm')">重置密码</button>
					</view>
				</uni-forms>
				
			</view>
		</view>
		
</template>

<script>
	export default {
	    data() {
	        return {
				getCodeText: '获取验证码',
				valiFormData: {
					phone: '',
					passward: '',
					repassward: '',
					code: '',
				},

				// 校验规则
				rules: {
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}]
					},
					
					repassword: {
						rules: [{
							required: true,
							errorMessage: '请再次输入密码'
						}, {
								validateFunction: function(rule, value, data, callback) {
									if (value != data.password) {
										callback('两次密码不一致')
									}
									return true
								}
							}]
					},
					code: {
						rules: [{
							required: true,
							errorMessage: '验证码不能为空'
						}]
					},
					phone: {
						rules: [{
							required: true,
							errorMessage: '手机号不能为空'
						}, 
						{
							format: 'phone',
							errorMessage: '请填写正确手机号'
						}]
					},
				},
				 
				
	            
	        }
	    },
		onReady() {
			// 设置自定义表单校验规则,必须在节点渲染完毕后执行
			this.$refs.valiForm.setRules(this.rules)
		},

	    methods: {

	        //表单
			submit(ref) {
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
				}).catch(err => {
					uni.showToast({
						icon: 'none',
						title: err[0].errorMessage
					});
				})
			},
			
			
	    },
	    
	}
</script>

你可能感兴趣的:(uni-app)