Home > Mobile >  How to prevent "Emoji & Symbols" from being inserted into an input
How to prevent "Emoji & Symbols" from being inserted into an input

Time:08-16

I'm using vue js but I'm open to any vanilla js suggestions as it all functions the same.

I want to prevent the system default emojis from being inserted into a text field via either the IOS keyboard or the (CMD CTRL SPACE) emoji panel.

When inserting, Apple OS creates an input event, which means by this time it's too late to prevent the insertion. We can't listen to keydown or keypress events either because the aforementioned event type is of input.

Should I be listening for another event type? Is there a way of disabling system emojis altogether from the context/keyboard menu?

My current solution would be to listen to the input event, and then sanitise the input by replacing the content captured from the first event with an empty string. I do this only after the first validation check from the more reliable keydown event passes. This solution does not feel elegant and I'm a bit surprised not to find anything about it online.

Here's the code that doesn't work because the event is too late:

<input type="text" v-model="text" @input="ignoreSystemEmojis($event)" />
ignoreSystemEmojis(event) {
  if (event.inputType === 'insertText') {      
    event.preventDefault();
  }
},

That obviously won't work because an input event occurs after the change.

And here's what I ended up:

<input type="text" v-model="text" @input="stripSystemEmojis($event)" />
stripSystemEmojis(event) {
  if (!/^[a-zA-Z\s&\d]*$/.test(event.data)) {
    this.text = this.text.replace(event.data, '');
  }
},

Help much appreciated!

CodePudding user response:

Listening to the input event and stripping unwanted characters sounds just fine. However you can use HTML5 pattern since you use a regex anyway:

<input type="text" v-model="text" pattern="[a-zA-Z\s&\d]" />

CodePudding user response:

You can have a keydown handler.

It cancels the keyboard event for invalid input.

new Vue({
  el: "#app",
  data: {
    text: "",
  },
  methods: {
    ignoreSystemEmojis(e) {
      if (!/^[a-zA-Z\s&\d]*$/.test(e.key)) {
        e.preventDefault();
      }
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-model="text" @keydown="ignoreSystemEmojis($event)" />
</div>

  • Related