赞
踩
由于微信小程序表单组件没有自带的验证功能,因此要针对每一项进行判断比较繁琐 因此封装了一个表单验证js, 具体验证规则根据自己所用到的进行添加,具体案例代码片段点击链接微信小程序表单验证完整代码片段
或者在微信小程序开发工具导入ID qGhpXdmZ7ydI
const form = { /* @formData 要验证的表单数据 @rules 验证规则 required必填 ***/ validation(formData, rules) { for (let item of rules) { let key = item.name; let ruleArr = item.rule; let msgArr = item.msg; if (!key || !ruleArr || ruleArr.length === 0 || !msgArr || msgArr.length === 0) continue for (let i = 0; i < ruleArr.length; i++) { let ruleItem = ruleArr[i]; let msg = msgArr[i]; if (!ruleItem || !msg) continue let value = null; if (ruleItem.indexOf(":") != -1) { let temp = ruleItem.split(":"); ruleItem = temp[0]; value = temp[1]; } let isError = false; switch (ruleItem) { case "required": isError = form.isNull(formData[key]); break; case "isEmail": isError = !form.isEmail(formData[key]); break; case "isTel": isError = !form.isTel(formData[key]); break; case "isSpecialWord": isError = !form.isSpecialWord(formData[key]); break; case "minLength": isError = !form.minLength(formData[key], value) break; case "maxLength": isError = !form.maxLength(formData[key], value) break; default: break; } if (isError) { wx.showToast({ title: msg, icon: 'none' }) return false } } } return true; }, isNull(value) { if (typeof value == 'object') { for (let prop in value) { if (typeof value[prop] == 'object') { for (let prop2 in value[prop]) { if (value[prop][prop2] === null || value[prop][prop2] === '' || value[prop][prop2] === undefined) { return true } else { return false } } } } } return (value === null || value === '' || value === undefined) ? true : false; }, isEmail(value) { return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/.test(value); }, isTel(value) { return /^(?:13\d|14\d|15\d|16\d|17\d|18\d|19\d)\d{5}(\d{3}|\*{3})$/.test(value); }, isSpecialWord(value) { //是否包含特殊字符 let regEn = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/, regCn = /[·!#¥(——):;“”‘、,|《。》?、【】[\]]/; return (regEn.test(value) || regCn.test(value)) ? false : true }, minLength(value, min) { return value.length >= Number(min) }, maxLength(value, max) { return value.length <= Number(max) } }; module.exports = { validation: form.validation };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。