How to Filter Text Input to Only Accept Numbers and a Dot with Vue.js?
<p>Sometimes, we want to filter text input to only accept numbers and a dot with Vue.js.</p>
<p>In this article, we’ll look at how to filter text input to only accept numbers and a dot with Vue.js.</p>
<h1>Filter Text Input to Only Accept Numbers and a Dot with Vue.js</h1>
<p>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.</p>
<p>The default action would be to accept the input.</p>
<p>For example, we can write:</p>
<pre>
<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></pre>
<p>to add a number input and the <code>isNumber</code> method which we set as the value of the <code>@keypress</code> directive to check the keys that are pressed.</p>
<p>We get the keyboard key character code from the <code>evt.which</code> or <code>evt.keyCode</code> property.</p>
<p><a href="https://hohanga.medium.com/how-to-filter-text-input-to-only-accept-numbers-and-a-dot-with-vue-js-ea78d010e59d">Read More</a></p>