表单规则校验器
const Validator = function ({ms}) {
this.pass = true;
this.ms = ms;
this.listen = []
}
// 添加验证规则逻辑
Validator.prototype.add = function({dom,rule,trigger}){
const tip = this.tip();
const p = document.createElement('div');
p.style.color = 'red';
p.style.display = 'none';
p.style.fontSize = '12px';
dom.parentElement.insertBefore(p,dom.nextElementSibling);
// 创建checkName规则的时候就把p提示标签嵌入他下面
const func = ()=>{
for (let i = 0; i < rule.length; i++) {
for (let j in rule[i]) {
if (this[j]) {
if (!this[j]({rule:rule[i],dom,tip,p})) {
return false;
}
}
}
}
};
dom.addEventListener(trigger,func)
// 为什么用函数呢,因为函数闭包内部保留变量
this.listen.push(func);
return this;
}
// 提示规则
Validator.prototype.tip = function(){
let timer;
return ({dom,message,p}) => {
p.style.display = '';
p.innerHTML = message;
dom.style.border = '1px solid red';
clearTimeout(timer);
timer = setTimeout(() => {
p.style.display = 'none';
dom.style.border = '';
timer = undefined;
}, this.ms);
}
}
// 提交之前检查所有
Validator.prototype.check = function(){
this.pass = true;
this.listen.forEach(e=>e())
return this.pass;
}
/*策略对象*/
const strategies = {
max({dom,rule,tip,p}){
if(dom.value.length > rule.max) {
tip({message:rule.message, dom,p});
this.pass = false;
return false;
}
return true;
},
min({dom,rule,tip,p}) {
if(dom.value.length < rule.min) {
// 不符合规则就提示
tip({message:rule.message, dom,p});
this.pass = false;
return false;
} else {
p.style.display = 'none';
return true;
}
}
};
for(let key in strategies){
Validator.prototype[key] = strategies[key];
}
const validator = new Validator({
ms: 1000
});
validator
.add({
dom: document.querySelector('.name'),
trigger: 'keyup',
rule: [
{ min: 1, message: '请输入名称' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符' }
]
})
.add({
dom: document.querySelector('.email'),
trigger: 'keyup',
rule: [
{ min: 1, message: '请输入名称' },
{ min: 3, max: 5, message: '长度在 3 到 5 个字符' }
]
})
document.querySelector('.submit').addEventListener('click',e=>{
e.preventDefault();
e.stopPropagation();
if(validator.check()){
console.log('submit!!!');
}
})