基于async-validator的表单验证

先在项目里install async-validator,然后把下面代码复制到一个js里

import AsyncValidator from 'async-validator'
const utils = {
	validate: (model, rules, callback, options) => {
		console.log(model)
		const initOptions = {
			showMessage: true
		}
		options = Object.assign({}, initOptions, options || {})
		let promise = null;
		if (typeof callback !== 'function') {
			promise = new Promise((resolve, reject) => {
				callback = function(valid) {
					valid ? resolve(valid) : reject(valid)
				}
			})
		}
		// 如果需要验证的fields为空,调用验证时立刻返回callback
		if ((!rules || rules.length === 0) && callback) {
			callback(true, null);
			return true
		}
		let errors = []
		const props = Object.keys(rules)
		let count = 0
		for (let i in props) {
			const prop = props[i]
			const value = utils.getValueByProp(model, prop)
			utils.validateItem(rules, prop, value, (err) => {
				if (err && err.length > 0) {
					errors = errors.concat(err)
				}
				// 处理异步校验,等所有校验都结束时再callback
				count++
				if (count === props.length) {
					if (errors.length > 0) {
						if (options.showMessage) {
							utils.showToast(errors[0].message)
						}
						callback(false, errors)
					} else {
						callback(true, null)
					}
				}
			})
		}
		if (promise) {
			return promise
		}
	},
	validateField: (model, rules, props, callback, options) => {
		const initOptions = {
			showMessage: true
		}
		options = Object.assign({}, initOptions, options || {})
		let promise = null;
		if (typeof callback !== 'function') {
			promise = new Promise((resolve, reject) => {
				callback = function(valid) {
					valid ? resolve(valid) : reject(valid)
				}
			})
		}
		props = [].concat(props)
		if (props.length === 0) {
			return
		}
		let errors = []
		let count = 0
		for (let i in props) {
			const prop = props[i]
			const value = utils.getValueByProp(model, prop)
			utils.validateItem(rules, prop, value, (err) => {
				if (err && err.length > 0) {
					errors = errors.concat(err)
				}
				// 处理异步校验,等所有校验都结束时再callback
				count++
				if (count === props.length) {
					if (errors.length > 0) {
						if (options.showMessage) {
							utils.showToast(errors[0].message)
						}
						callback(false, errors)
					} else {
						callback(true, null)
					}
				}
			})
		}
		if (promise) {
			return promise
		}
	},
	validateItem(rules, prop, value, callback) {
		if (!rules || JSON.stringify(rules) === '{}') {
			if (callback instanceof Function) {
				callback();
			}
			return true;
		}
		const propRules = [].concat(rules[prop] || []);
		propRules.forEach((rule) => {
			if (rule.pattern) {
				rule.pattern = new RegExp(rule.pattern)
			}
		})
		const descriptor = {
			[prop]: propRules
		};
		const validator = new AsyncValidator(descriptor);
		const model = {
			[prop]: value
		};
		validator.validate(model, {
			firstFields: true
		}, (errors) => {
			callback(errors);
		});
	},
	getValueByProp: (obj, prop) => {
		let tempObj = obj;
		prop = prop.replace(/\[(\w+)\]/g, '.$1').replace(/^\./, '');
		let keyArr = prop.split('.');
		let i = 0;
		for (let len = keyArr.length; i < len - 1; ++i) {
			if (!tempObj) break;
			let key = keyArr[i];
			if (key in tempObj) {
				tempObj = tempObj[key];
			} else {
				break;
			}
		}
		return tempObj ? (typeof tempObj[keyArr[i]] === 'string' ? tempObj[keyArr[i]].trim() : tempObj[keyArr[i]]) :
			null
	},
	showToast: (message) => {
		uni.showToast({
			title: message,
			icon: 'none'
		})
	}
}

export default utils

最后用法:

info:{
	orderNum:'',
},
rule:{
	orderNum: {
		required: true,
		message: '请输入运单号'
	},
},
utils.validate(this.info, this.rule, (res, errors) => {})

info为数据,rule为验证规则

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值