SoFunction
Updated on 2025-04-07

Globally restrict special characters input in Vue

vue globally restricts input special characters

background:

Form input encountered during development often limits the input of special characters to meet the requirements of security testing.

Process each text box individually

<template>
  <el-input 
    v-model="content" 
    placeholder="Please enter"
    @change="vaidateEmoji">
  </el-input>
</template>

<script> 
export default {
  methods: {
    vaidateEmoji() {
       const regRule = /[`~^!@#$€£₤%^&*()_\-+=<>?:"{}|.\/;'\\[\]·~!……@#¥¥%*()\-+={}|《》?:“”【】‘']/im;
        = (regRule, '');
    },
  },
}
</script>

In this way, each input box is processed separately, which is a lot of work and difficult to maintain, so you need to customize a command to achieve this requirement uniformly.

Custom directives are handled globally (recommended)

  • Custom restriction input special character instructions
// 
import Vue from 'vue';

// Special characters are prohibited('emoji', {
  bind: function (el, binding, vnode) {
    // Regular rules can be customized according to requirements    const regRule = /[`~^!@#$€£₤%^&*()_\-+=<>?:"{}|.\/;'\\[\]·~!……@#¥¥%*()\-+={}|《》?:“”【】‘']/im;
    let $inp = findEle(el, 'input') || findEle(el, 'textarea');
    el.$inp = $inp;
    $ = function (event) {
      let val = $;
      $ = (regRule, '');
      trigger($inp, 'input');
    }
    $('keyup', $);
  },
  unbind: function (el) {
    el.$('keyup', el.$);
  }
});
 
const findEle = (parent, type) => {
  return () === type ? parent : (type)
};
 
const trigger = (el, type) => {
  const e = ('HTMLEvents');
  (type, true, true);
  (e);
};
  • Introduce this custom component in
import '@/directives/';
  • Use in components

Add v-emoji to the input box (multi-line text box) that needs to be checked

<el-input 
  v-emoji
  v-model="content" 
  placeholder="Please enter">
</el-input>

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.