1

I am trying that in an input only letters can be written and that special characters or numbers cannot be written, for now I have succeeded unless if I write "`" or "´" they continue to be written. How can I stop them from appearing?

this is what i did

https://codesandbox.io/s/kind-cannon-vccjb?file=/src/App.vue:0-699

JesúsDel
  • 103
  • 1
  • 7
  • Does this answer your question? [Filter input text to enter only number and not even decimal](https://stackoverflow.com/questions/53754772/filter-input-text-to-enter-only-number-and-not-even-decimal) – yqlim May 30 '21 at 20:36
  • Does this help you? https://stackoverflow.com/questions/20783093/allowing-only-alphabets-in-text-box-using-java-script/23711474 – fynsta May 30 '21 at 20:37
  • @yqlim It is similar, but in that problem it is with numbers and mine is with letters, I have tried it and it does not work. – JesúsDel May 30 '21 at 20:44
  • @fynsta no, since the problem is that I don't know how to prevent "`" or "´" from being displayed. thank you anyway – JesúsDel May 30 '21 at 20:48
  • @JesúsDelRío the linked question is exactly the same with yours. All you need to do is substitute the "numbers" with your "letters". – yqlim May 30 '21 at 20:51
  • @yqlim I did this test, and it doesn't work as it only works if I change type = "text" to type = "number" https://codesandbox.io/s/no-caracteres-especiales-forked-hkrr3 – JesúsDel May 30 '21 at 20:58
  • You can whitelist the characters you want. The problem with accents is they are on valid keys, so you get an error for the modifier key, but it allows the secondary keypress. – pilchard May 30 '21 at 21:10
  • @pilchard and how I do it? – JesúsDel May 30 '21 at 21:12
  • 1
    You can use `` to limit the type of the input that's allowed. You can check [here](https://www.html5pattern.com/Names) for useful patterns – ljubadr May 30 '21 at 22:35

1 Answers1

1

Your code seemed to be working fine for me, but it was only handling keyboard presses and didn't work when you pasted.
A better way would be to validate the input and fix it when the input value changes with @input since you were already binding the results to this.firstname.

<template>
  <div id="app">
    Only letter
    <input type="text" v-model="firstName" @input="prueba" />
    <br />
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    firstName: "",
  }),
  methods: {
    prueba() {
      //this will replace every non letter input with an empty string leading to removing it
      this.firstName = this.firstName.replaceAll(/[^a-zA-Z]/g, "");
      //you can also do your uppercase change here, no need to do it in update
      this.firstName = this.firstName.toUpperCase()
    },
  },
};
</script>

note that you can also combine both lines in one such as

this.firstName = this.firstName.replaceAll(/[^a-zA-Z]+/g, "").toUpperCase();
Jimmar
  • 4,194
  • 2
  • 28
  • 43