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&rsquo;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&rsquo;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> &lt;template&gt; &lt;div id=&quot;app&quot;&gt; &lt;input v-model=&quot;num&quot; @keypress=&quot;isNumber($event)&quot; /&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; export default { name: &quot;App&quot;, data() { return { num: 0, }; }, methods: { isNumber(evt) { const charCode = evt.which ? evt.which : evt.keyCode; if ( charCode &gt; 31 &amp;&amp; (charCode &lt; 48 || charCode &gt; 57) &amp;&amp; charCode !== 46 ) { evt.preventDefault(); } }, }, }; &lt;/script&gt;</pre> <p>to add a number input and the&nbsp;<code>isNumber</code>&nbsp;method which we set as the value of the&nbsp;<code>@keypress</code>&nbsp;directive to check the keys that are pressed.</p> <p>We get the keyboard key character code from the&nbsp;<code>evt.which</code>&nbsp;or&nbsp;<code>evt.keyCode</code>&nbsp;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>