How to filter input text only accept number and dot with Vue.js?

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

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

How to filter input text only accept number and dot with Vue.js?

To filter input text only accept number and dot with Vue.js, we can listen for the keypress event and validate the input in the keypress event handler.

For instance, we write

<template>
  <div id="app">
    <input v-model="message" @keypress="isNumber($event)" />
  </div>
</template>

<script>
//...
export default {
  data() {
    return {
      message: 1234.34,
    };
  },
  methods: {
    isNumber(evt) {
      const charCode = evt.keyCode;
      if (
        charCode > 31 &&
        (charCode < 48 || charCode > 57) &&
        charCode !== 46
      ) {
        evt.preventDefault();
      } else {
        return true;
      }
    },
  },
};
</script>

to add the input with the @keypress directive to listen to the keypress event.

We run isNumber if we enter anything into the input.

In it, we check if the key codes aren’t in the ranges for numbers and the period.

If it’s not, we call preventDefault to discard the characters.

Otherwise, we return true to keep them.

Conclusion

To filter input text only accept number and dot with Vue.js, we can listen for the keypress event and validate the input in the keypress event handler.