7

I'd like a text input to accept only a sequence of numbers. Any other char should be ignored silently. Here's a simplified version of my component:

<template>
  <div id="app">
    <input :value="tel" @input="setTel" placeholder="only numbers" />
    <p>{{ tel }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    tel: "1234"
  }),

  methods: {
    setTel(v) {
      const val = v.target.value.replace(/[^0-9]/g, "");
      this.tel = val;
      /*this.tel = v.target.value = v.target.value.replace(/[^0-9]/g, "");*/
    }
  }
};
</script>

In React, there's the concept of controlled components, but I can't seem anything similar in Vue.

The workaround I found (which you can see in comments) is to modify the value of the input element manually, but it kind of defeats the purpose of using Vue.

I've also tried using v-model, but the issue remains.

codesandbox.

4
  • try to use <input type='number' ... Mar 16, 2019 at 10:55
  • You could actually achieve this with plain JS, function formatNumber(element) { element.value = Number(element.value.replace(/[^0-9]/g, '')).toLocaleString(undefined, { maximumFractionDigits: 2 }); } Also try using the keyUp event.
    – Ugo Okoro
    Mar 16, 2019 at 10:58
  • @BoussadjraBrahim need to use type='text, this case is more general than just ^[0-9]*$
    – maioman
    Mar 16, 2019 at 10:59
  • @UgoOkoro that's like the workaround I found, but modifying the input element directly doesn't feel right. Inspecting this.tel in the example you can see it gets the correct value, it's just the view not updating...
    – maioman
    Mar 16, 2019 at 11:05

6 Answers 6

4
<template>
  <div id="app">
    <input v-model="tel" v-on:keyup="setTel" placeholder="only numbers" />
    <p>{{ tel }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    tel: "1234"
  }),

  methods: {
    setTel(v) {
      const val = v.target.value.replace(/[^0-9]/g, "");
      this.tel = val;
      /*this.tel = v.target.value = v.target.value.replace(/[^0-9]/g, "");*/
    }
  }
};
</script>

I took a look at your sandbox and made a few modifications, Please check to see if this is what you want, the view is now updated.

2
  • thanks for the effort, but in your solution letters do pass through to the input and this is not optimal.
    – maioman
    Mar 16, 2019 at 11:31
  • Sometimes, it appears to be necessary to use this.$forceUpdate() to make vue override what the user just typed. Apparently, vue needs to re-render to prevent the user from typing something into the input field. Mar 2, 2020 at 20:19
2

well you can use <input type=number... like every one said here but if you want to handle manually than what you can do is change your el.target.value in handler like

<template>
  <div id="app">
    <input
      :value="tel"
      @input="setTel"
      placeholder="0"
    />
    <p>{{ tel }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    tel: "1234"
  }),

  methods: {
    setTel(v) {
      v.target.value = v.target.value.replace(/[^0-9]/g, "");
      this.tel = v.target.value
      /*this.tel = v.target.value = v.target.value.replace(/[^0-9]/g, "");*/
    }
  }
};
</script>

and for the part where vue is showing text in your input is because when you assign same value after replacing text vue doesn't refresh the state of that particular element to avoid extra rendering

1
  • You're posting the workaround I mention in OP as an answer :). I don't want the value to get assigned to v.target.value, type number in not the point here, this can be generalized to any kind of rule.
    – maioman
    Mar 16, 2019 at 13:03
1

Instead of handling keyup (which would allow the key to reach the input), you should handle keydown. The handler should call event.preventDefault() and event.stopPropagation() to ignore the key:

// ignore non-numeric keys
if (!/\d/.test(v.key)) {
  v.preventDefault()
  v.stopPropagation()
  return false
}

The input should allow meta keys through (e.g. to allow copy-paste or delete):

// allow all meta keys (including Backspace) to pass through
if (v.metaKey || /(Backspace|Meta)/g.test(v.key)) {
  console.log('ignoring', v.key)
  return
}

In addition, this input should handle the input event in order to filter copy-pasted values.

// template
<input v-model="tel" @input="onInput" v-on:keydown="setTel" />

// script
onInput(e) {
  if (e.inputType !== 'insertText' && /[^0-9]/g.test(e.target.value)) {
    const val = e.target.value.replace(/[^0-9]/g, "");
    this.tel = val;
    e.preventDefault()
    e.stopPropagation()
    return false
  }
}

demo

0

There a couple of things you can do:

  • set the input's type to number <input type=number. This will block the user from entering any character except number. This is handled by the browser.
  • you can use v-model and also add a listener @change to check the value and modify the model accordingly. Node that you can add the number modifier on the model so vue casts the input to a number `
  • use a validation framework like vuelidate
0

You answered your own question by setting the value on the input with the "workaround". If you wanted it to work just like React Controlled Components, you could just set the target input's value to the value from the data model unless it actually changes the data model. In this manner, the Vue data model would be your single source of truth.

<template>
  <div id="app">
    <input 
      v-bind:value="tel" 
      v-on:input="handleInputTel" 
      placeholder="only numbers" 
    />
    <p>{{ tel }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data: () => ({
    tel: "1234"
  }),

  methods: {
    handleInputTel(v) {
      if (validate(v.target.value)) this.tel = v.target.value; 
      else v.target.value = this.tel;
    }
  }
};
</script>
0

Because the strategy of VUE to render, if the state is not different with old, this input component do not re render. But the input DOM had changed. So, you can use $forceUpdate on input event.

setTel(v) {
      const val = v.target.value.replace(/[^0-9]/g, "");
      this.tel = val;
      this.$forceUpdate();
    }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.