How to Filter Text Input to Only Accept Numbers and a Dot with Vue.js?

Sometimes, we want to filter text input to only accept numbers and a dot with Vue.js.

In this article, we’ll look at how to filter text input to only accept numbers and a dot with Vue.js.

Filter Text Input to Only Accept Numbers and a Dot with Vue.js

We can filter text input to only accept numbers and a dot with Vue.js by checking for keycodes which aren’t numbers and preventing the default action in those case.

The default action would be to accept the input.

For example, we can write:

<template>
  <div id="app">
    <input v-model="num" @keypress="isNumber($event)" />
  </div>
</template>
<script>
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    isNumber(evt) {
      const charCode = evt.which ? evt.which : evt.keyCode;
      if (
        charCode > 31 &&
        (charCode < 48 || charCode > 57) &&
        charCode !== 46
      ) {
        evt.preventDefault();
      }
    },
  },
};
</script>

to add a number input and the isNumber method which we set as the value of the @keypress directive to check the keys that are pressed.

We get the keyboard key character code from the evt.which or evt.keyCode property.

Read More