0

I want to block writing special characters in input of Vue.
First, I made a function like below.

blockSpecialChar(e) {
      console.log(e.keyCode);
      const k = e.keyCode;
      return (
        (k > 64 && k < 91) ||
        (k > 96 && k < 123) ||
        k == 8 ||
        (k >= 48 && k <= 57)
      );
    }

And I connect it with the code below.

         <input
            type="test"
            placeholder="phone"
            v-model="pin.phoneNumber"
            v-on:keypress.prevent="blockSpecialChar(e)"
          />

But when I type, it says 'e is not defined'. How can I make this correctly? Thank you so much for reading.

2
  • 1
    v-on:keypress.prevent="blockSpecialChar" or v-on:keypress.prevent="e => blockSpecialChar(e)" Commented Sep 19, 2019 at 12:14
  • Thank you so much. 'e' is defined well. But the problem is that input doesn't have anything even though I type something. Is my blockspecialchar function correct? Commented Sep 19, 2019 at 12:25

2 Answers 2

2

you dont need to pass params when passing a method,

<input
    type="test"
    placeholder="phone"
    v-model="pin.phoneNumber"
    v-on:keypress.prevent="blockSpecialChar"
/>

and this code should work now

blockSpecialChar(e) {
      console.log(e.keyCode);
      const k = e.keyCode;
      return (
        (k > 64 && k < 91) ||
        (k > 96 && k < 123) ||
        k == 8 ||
        (k >= 48 && k <= 57)
      );
    }
Sign up to request clarification or add additional context in comments.

Comments

0

You do not need to pass e explicitly to the keypress function.

Just write:

<input
    type="test"
    placeholder="phone"
    v-model="pin.phoneNumber"
    v-on:keypress.prevent="blockSpecialChar"
/>

Because this is a callback function, e will be automatically initialized in your function block.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.