In this tutorial, we will learn how to use Vue 3 to accept only numbers in an input field. We will provide two examples to achieve this. In the first example, we will use Vue 3 Composition API and regex. In the second example, we will use Vue 2 Options API and the charcode method.
Example 1 : Accept Only Numbers in Input Type Text using Vue 3
In this example, we will see how to prevent non-numeric characters in an input field using Vue 3 and the regex method.
Vue 3 Input Number Only
<script type="module">
const {createApp,ref} = Vue
createApp({
setup() {
const numericInput = ref("");
function filterNonNumeric(event) {
numericInput.value = numericInput.value.replace(/\D/g, '');
}
return {
numericInput,
filterNonNumeric
};
}
}).mount('#app')
</script>
Example 2: How to Make Input Accept only Numbers in Vue Js (Options Api)?
This code below demonstrates how to allow only numbers in a text field, such as a phone number. We use the Vue charcode method to achieve this.
Vue Js Only Allow Numbers in Input
<script type="module">
const app = Vue.createApp({
data() {
return {
numericInput: ""
}
},
methods: {
filterNonNumeric(event) {
return (event.charCode >= 48 && event.charCode <= 57) || event.charCode === 0 ? true : event.preventDefault();
}
}
});
app.mount('#app');
</script>