前端开发最常碰到的就是输入框,经常要做各种验证,本公司惯用的需求是直接屏蔽特定字符的输入,如禁止非数字输入,特殊符号输入,空格输入等,这些功能反复使用,做成指令的形式,直接调用,非常方便,上代码:
目录结构很简单:
1、项目文件夹里新建directives文件夹,所有指令都放在这个文件夹里
2、input-filter文件夹放具体指令,在其下建两个文件:
a、inputFilter.js实现主体功能
b、index.js负责封装,职责分明
inputFilter.js代码:
/** * 实现功能 * 1、默认情况下只禁止空格输入 * 2、限制只能输入整数 * 3、限制只能输入整数和小数(价格类) * 4、限制只能输入手机号 * 5、限制最大值和最小值(抛出错误给回调函数) */ const addListener = function(el, type, fn) { el.addEventListener(type, fn, false) } const spaceFilter = function(el) { addListener(el, 'keyup', () => { el.value = el.value.replace(/s+/, '') }) } const intFilter = function(el) { addListener(el, 'keyup', () => { el.value = el.value.replace(/D/g, '') }) } const priceFilter = function(el) { addListener(el, 'keyup', () => { el.value = el.value.replace(/[^d.]*/g, '') if (isNaN(el.value)) { el.value = '' } }) } const specialFilter = function(el) { addListener(el, 'keyup', () => { el.value = el.value.replace(/[^a-zA-0-9u4E00-u9FA5]/g, '') }) } const phoneFilter = function(el) { addListener(el, 'blur', () => { if (!el.value) { return } const phoneReg = new RegExp('^(13|14|15|16|17|18|19)[0-9]{9}$') if (!phoneReg.test(el.value)) { alert('手机号输入错误') el.value = '' } }) } const urlFilter = function(el) { addListener(el, 'blur', () => { if (!el.value) { return } const urlReg = /(^#)|(^http(s*)://[^s]+.[^s]+)/ if (!urlReg.test(el.value)) { alert('url输入错误') el.value = '' } }) } export default { bind(el, binding) { if (el.tagName.toLowerCase() !== 'input') { el = el.getElementsByTagName('input')[0] } spaceFilter(el) switch (binding.arg) { case 'int': intFilter(el) break case 'price': priceFilter(el) break case 'special': specialFilter(el) break case 'phone': phoneFilter(el) break case 'url': urlFilter(el) break default: break } } }
index.js代码:
import inputFilter from './inputFilter' const install = function(Vue) { Vue.directive('inputFilter', inputFilter) } if (window.Vue) { window.inputFilter = inputFilter Vue.use(install) } inputFilter.install = install export default inputFilter
组件引用:
import inputFilter from '@/directives/input-filter/index.js' // 引入 <el-input v-input-filter v-model="inputSpaceFilter" placeholder="空格无法输入"></el-input> <el-input v-input-filter:int v-model="inputIntFilter" placeholder="只能输入整数"></el-input> <el-input v-input-filter:price v-model="inputPriceFilter" placeholder="只能输入价格"></el-input> <el-input v-input-filter:special v-model="inputSpecialFilter" placeholder="过滤特殊字符"></el-input> <el-input v-input-filter:phone v-model="inputPhoneFilter" placeholder="只能输入手机号"></el-input> <el-input v-input-filter:url v-model="inputUrlFilter" placeholder="只能输入网址"></el-input> export default { directives: { inputFilter } }
效果图: