Skip to content
Advertisement

How to prevent user from entering value below 1 in Vue 3 number input

I am attempting to set up a number input field in Vue 3 that prevents the user from entering a value below 1. So far I have the following input with min = 1 to prevent clicking the input arrows below 1:

<input min="1" type="number" />

However, the user can still manually enter 0 or a negative number. How can I prevent the user entering a number below 1?

Advertisement

Answer

You can check value on keyup:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const numValue = ref(null)
    const setMin = () => {
      if(numValue.value < 1) numValue.value = null
    }
    return { numValue, setMin }
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <input @keyup="setMin" min="1" v-model="numValue" type="number" />
</div>
Advertisement