Filter out letters from an input, to only keep numbers


I’m trying to build an input that can only have numbers as value.

I did something like this :

<input @input="handleInput($event)" :value="value">


data() {
    return {
        value: null

methods: {
    handleInput(event) {
        this.value =\D/g, "")

But I can still type letters,

So I created a CodeSandbox so you can try by yourself :

All code is in the App.vue file.
In this sandbox you can manipulate the input value in order to have it :

  • uppercase (it works)
  • only numeric (it doesn’t work)

Thanks for your help

You can use input with @keyup.native=" " and then .replace(/[^\d]/g, ‘’) deletes letters immediately, but leaves numbers.

Thanks zany,

Issue is still here when using keyup.

The 3rd section (bonus) of the codesandbox,seems like a vue related bug, maybe I should ask this question on the github repository ?

You can try. :slight_smile:

Copy pasted from the issue:

This is working as expected: by filtering out letters before setting myNumericValue, this variable never changes and never triggers a re render, so the value on the input is preserved.

One way to get around this is to force update with this.$forceUpdate() after changing the value. A better way is to reset the input’s value only:

const val = $[^\d]/g, ""); // strips letters, keeps numbers
      if (val === this.numericValue) $ = val
      else this.numericValue = val
1 Like