当前位置:网站首页>小程序表单校验封装
小程序表单校验封装
2022-07-01 23:02:00 【akko_】
validate.js文件:
class Validate {
constructor(rules, form) {
if (new.target === Validate) {
this.valid = true // 校验结果
this.errorMessage = [] // 错误信息
if (rules === undefined || typeof rules !== 'object') {
throw new Error('必须传入规则对象');
} else {
this.rules = rules // 规则对象
}
if (form === undefined || typeof form !== 'object') {
throw new Error('必须传入表单对象');
} else {
this.form = form // 表单对象
}
} else {
throw new Error('必须使用 new 命令生成实例');
}
}
// 校验必填
checkRequired(field) {
if (!field) return false
return true
}
// 校验身份证
checkIdCard(field) {
if (!/^[1-9]\d{5}(?:18|19|20)\d{2}(?:0[1-9]|10|11|12)(?:0[1-9]|[1-2]\d|30|31)\d{3}[\dXx]$/g.test(field))
return false
return true
}
// 校验手机号(最宽松)
checkTel(field) {
if (!/^(?:(?:\+|00)86)?1\d{10}$/g.test(field)) return false
return true
}
// 校验邮箱
checkEmail(field) {
if (!
/^(([^<>()[\]\\.,;:\[email protected]"]+(\.[^<>()[\]\\.,;:\[email protected]"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g
.test(field)) return false
return true
}
// 校验min
checkMin(min, field) {
if (typeof min !== "number" || typeof field !== "number") return false
if (field < min) return false
return true
}
// 校验max
checkMax(max, field) {
if (typeof max !== "number" || typeof field !== "number") return false
if (field > max) return false
return true
}
// 进行校验
__validateForm() {
// 遍历规则对象去表单数据匹配
for (const ruleItemKey of Object.keys(this.rules)) {
let ruleItem = this.rules[ruleItemKey]
for (let i = 0; i < ruleItem.length; i++) {
if (ruleItem[i].required !== undefined && ruleItem[i].required) {
this.valid = this.valid && this.checkRequired(this.form[ruleItemKey])
if (!this.checkRequired(this.form[ruleItemKey])) this.errorMessage.push(ruleItem[i].message)
}
// 该字段必填或者该字段不为空
if (ruleItem[i].required || this.form[ruleItemKey]) {
if (ruleItem[i].idcard !== undefined && ruleItem[i].idcard) {
this.valid = this.valid && this.checkIdCard(this.form[ruleItemKey])
if (!this.checkIdCard(this.form[ruleItemKey])) this.errorMessage.push(ruleItem[i].message)
}
}
if (ruleItem[i].required || this.form[ruleItemKey]) {
if (ruleItem[i].tel !== undefined && ruleItem[i].tel) {
this.valid = this.valid && this.checkTel(this.form[ruleItemKey])
if (!this.checkTel(this.form[ruleItemKey])) this.errorMessage.push(ruleItem[i].message)
}
}
if (ruleItem[i].required || this.form[ruleItemKey]) {
if (ruleItem[i].email !== undefined && ruleItem[i].email) {
this.valid = this.valid && this.checkEmail(this.form[ruleItemKey])
if (!this.checkEmail(this.form[ruleItemKey])) this.errorMessage.push(ruleItem[i].message)
}
}
if (ruleItem[i].required || this.form[ruleItemKey]) {
if (ruleItem[i].min !== undefined && ruleItem[i].min) {
this.valid = this.valid && this.checkMin(ruleItem[i].min, this.form[ruleItemKey])
if (!this.checkMin(ruleItem[i].min, this.form[ruleItemKey])) this.errorMessage.push(
ruleItem[i].message)
}
}
if (ruleItem[i].required || this.form[ruleItemKey]) {
if (ruleItem[i].max !== undefined && ruleItem[i].max) {
this.valid = this.valid && this.checkMax(ruleItem[i].max, this.form[ruleItemKey])
if (!this.checkMax(ruleItem[i].max, this.form[ruleItemKey])) this.errorMessage.push(
ruleItem[i].message)
}
}
}
}
return this.valid
}
}
export default Validate
调用方式:
import validate from "@/utils/validate.js"
lef form = {
phone:"",
code:""
}
const rules = {
phone: [{
tel: true,
message: '手机号输入不正确'
}, {
required: true,
message: '手机号不能为空'
}],
code: [{
required: true,
message: '验证码不能为空'
}]
}
const valid = new validate(rules, {
phone: phone.value,
code: code.value
})
if (valid.__validateForm()) {
// 验证成功执行
}else{
// 验证失败提示错误
uni.showToast({
title: valid.errorMessage.join(","),
icon: "none",
duration: 2000
})
}
边栏推荐
- CADD course learning (3) -- target drug interaction
- 硅谷产品实战学习感触
- CADD课程学习(3)-- 靶点药物相互作用
- Redis data types and application scenarios
- Commemorate becoming the first dayus200 tripartite demo contributor
- Wechat personal small store one click opening assistant applet development
- 云信小课堂 | IM及音视频中常见的认知误区
- 每日三题 6.29
- Glass mosaic
- Matplotlib common charts
猜你喜欢
How to display real-time 2D map after rviz is opened
from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
什么是马赛克?
Experience of practical learning of Silicon Valley products
[MySQL] basic use of explain and the function of each column
Jielizhi Bluetooth headset quality control and production skills [chapter]
玻璃马赛克
Zero foundation tutorial of Internet of things development
Redis~02 缓存:更新数据时如何保证MySQL和Redis中的数据一致性?
flutter Unable to load asset: assets/images/888. png
随机推荐
Jerry's question about long press boot detection [chapter]
从第三次技术革命看企业应用三大开发趋势
神经网络物联网的发展趋势和未来方向
每日三题 6.30
How to display real-time 2D map after rviz is opened
Microservice stability management
Create Ca and issue certificate through go language
[applet] realize the left and right [sliding] list through the scroll view component
[micro service sentinel] sentinel integrates openfeign
Wechat personal small store one click opening assistant applet development
dat.GUI
AirServer最新Win64位个人版投屏软件
每日三题 6.28
物联网现状及未来发展趋势
距离度量 —— 汉明距离(Hamming Distance)
Daily three questions 6.29
SWT / anr problem - SWT causes kernel fuse deadlock
【微服务|Sentinel】sentinel整合openfeign
Which securities company is better and which is safer to open a securities account
"35 years old, the boss of the company, with a monthly salary of 20000, give away takeout": the times abandoned you, not even saying goodbye