媒介
在项目中经常会用到表单的校验,前端校验会削减对服务器的压力并且能提拔用户体验,到达种种交互效果
演习: 通用校验函数编写
思索: 平常校验有哪几种状况
从上至下,提醒语只需一个位置只显现毛病的第一条(标红/不标红毛病的相干项)
每一个元素下方提醒当前元素的毛病提醒 不合适以弹框的情势显现
提醒语在元素右边 弹框平安高度640px之内
递次详细交互?首先得看产物的需求
从上至下校验,只提醒按递次毛病的第一个毛病信息,落空核心/值转变立马校验(条件是已点击过提交按钮了),标红/不标红响应毛病的元素
同上,只是毛病提醒以toast情势显现
校验经由过程再激活提交按钮,某些还要制止反复接见(用定时器设置制止时候长度) 这类合适校验内容少且校验划定规矩是人人广泛有共鸣的
一、从上至下校验
二、对应校验
思绪
思绪:表驱动法
设想校验提醒信息表 校验划定规矩表 校验元素表(表的健值对必须要一致,轻易经由过程雷同的健猎取对应表值)
校验实行的递次,是不是中缀校验的标志,校验函数返回值
向外暴露毛病回调函数
// 主函数设想:validate(obj, fields, format, callback)
// 申明:
// 1.obj 要校验的元素对象
let obj = {
'email':'',
'password': ''
};
// 2.fields要校验的花样type和毛病提醒信息errMsg
let fields = {
'email': {
'type': 'emailFormat',
'errMsg': '邮箱花样毛病'
},
'password': {
'type': 'passwordFormat',
'errMsg': '暗码花样毛病'
}
};
// 3.format校验的花样对应的函数
let format = {
'emailFormat': isEmail,
'passwordFormat': isPassword,
'emptyFormat': isEmpty
};
// 4.毛病回调
const callback = (errMsg, key) => {
console.log(errMsg, key);
};
// 5.实行递次 函数返回值已中缀标志
// isBreak是不是中缀当前某个元素的校验
// result 花样校验的效果 true标示校验准确
// isSuccess 校验主函数的返回值 true示意校验胜利
// callback 校验失利要实行的操纵
// 一、从上至下校验
map(() => {
if (isBreak) {
return false
}
})
if (result) {
// 校验胜利
} else {
// 校验失利
callback(errMsg, key);
isBreak = true; // 只需有一个校验失足函数就返回校验失利
isSuccess = false;
}
// 二、对应校验
// 去掉推断是不是中缀当前校验即可
代码
// 校验函数
const isEmpty = function (str) {
return str === null || typeof str === "undefined" || str.replace(/^\s+|\s+$/g, '') ? true : false
};
const isEmail = function (str) {
return pattern.email.test(str)
};
const isPassword = function (str) {
return pattern.password.test(str)
};
// 毛病回调
const callback = (errMsg, key) => {
console.log(errMsg, key);
};
// 主函数
const validate = (obj, fields, format, callback) => {
let isSuccess = true;
let isBreak = false; // 是不是中缀校验的标志
// obj要校验的对象,fields校验提醒信息,format校验的花样,callback校验毛病的回调函数
// 函数返回值
// 经由过程健一致来猎取须要的对应的值
Object.keys(obj).map((key) => {
// 检测是不是中缀map轮回
if (isBreak) {
return false
}
let formats = fields[key]['type']; // 猎取校验的花样
let errMsg = fields[key]['errMsg']; // 猎取校验的毛病提醒语
let validateFun = format[formats]; // 猎取校验花样的函数
let value = obj[key]; // 要校验对象的值
let result = validateFun(value); // 实行校验函数,传参数(要校验对象的值) 返回true为校验当前校验经由过程
if (result) {
// 校验胜利
console.log('校验胜利')
} else {
// 校验失利
callback(errMsg, key);
isSuccess = false; // 只需有一个校验失足函数就返回校验失利
isBreak = true;
console.log('只需有一个毛病就退出当前校验');
}
});
return isSuccess; // 只需有一个毛病校验就不经由过程
};
// 用法 对应校验须要合营ui一同运用 callback(errMsg, key) key为校验的元素毛病信息ui应与其相干联是不是显现
// 1.obj 要校验的元素对象
let obj = {
'email':'',
'password': ''
};
// 2.fields要校验的花样type和毛病提醒信息errMsg
let fields = {
'email': {
'type': 'emailFormat',
'errMsg': '邮箱花样毛病'
},
'password': {
'type': 'passwordFormat',
'errMsg': '暗码花样毛病'
}
};
// 3.format校验的花样对应的函数
let format = {
'emailFormat': isEmail,
'passwordFormat': isPassword,
'emptyFormat': isEmpty
};
// 4.挪用
console.log(validate(obj, fields, format, callback));