程序谷 认真生活 享受生活

Vue中input全局禁止输入特殊符号

⚠️ 本文最后更新于2024年01月10日,已经过了570天没有更新,若内容或图片失效,请留言反馈
UXD1SY
https://blog.51cto.com/zhengys/6991950

新建一个工具类

//special.js
 import Vue from 'vue';

// 禁止输入特殊字符
Vue.directive('special', {
    bind: function (el, binding, vnode) {
        // 正则规则可根据需求自定义
        // const regRule = /[`~^!@#$€£₤%^&*()_\-+=<>?:"{}|.\/;'\\[\]·~!……@#¥¥%*()\-+={}|《》?:“”【】‘']/im;
        const regRule = /[<>"'=?!\/\\]/im;
        let $inp = findEle(el, 'input') || findEle(el, 'textarea');
        el.$inp = $inp;
        $inp.handle = function (event) {
            let val = $inp.value;
            $inp.value = val.replace(regRule, '');
            trigger($inp, 'input');
        }
        $inp.addEventListener('keyup', $inp.handle);
    },
    unbind: function (el) {
        el.$inp.removeEventListener('keyup', el.$inp.handle);
    }
});

const findEle = (parent, type) => {
    return parent.tagName.toLowerCase() === type ? parent : parent.querySelector(type)
};

const trigger = (el, type) => {
    const e = document.createEvent('HTMLEvents');
    e.initEvent(type, true, true);
    el.dispatchEvent(e);
}

引入工具类

//在main.js中引入
import '@/utils/special'

使用

//在input中直接使用v-special
<el-input v-model="xx" v-special />
By 大芃展翅 On
此页面评论区已关闭
程序谷 |  蜀ICP备2020031553号-1