We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
表单规则校验器
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!!!'); } })
The text was updated successfully, but these errors were encountered:
plh97
No branches or pull requests
前言
表单规则校验器
需求
The text was updated successfully, but these errors were encountered: