[SOLVED] How to limit a max number for a NUMBER input in vue?

Issue

This Content is from Stack Overflow. Question asked by Khant

I am now trying to create a new input which will reject if the number user type in exceed the limit but it is not working the

let say the max number is 99
Currently my best way is to create something like this

<input
    type="text"
    :maxlength="2"
    aria-controls="none"
    class="number-field-input"
    inputmode="numeric"
    pattern="/d+"
    v-model="inputOne"
  />

This will limit the max number to 99 since the max length is 2 but I don’t want something like this I want something like this but its not working

<input
        type="number"
        min="1"
        max="99" //may not be 99 but something between 1 and 99
        aria-controls="none"
        class="number-field-input"
        inputmode="numeric"
        pattern="/d+"
        v-model="inputOne"
   />



Solution

You can use watcher :

const { ref, watch } = Vue
const app = Vue.createApp({
  setup() {
    let inputOne = ref(0)
    watch(inputOne,
      (newValue) => {
        inputOne.value = newValue > 99 ? 99 : newValue
      },
    );
    return { inputOne };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
<div>
  <input
    type="number"
    min="1"
    max="99" 
    aria-controls="none"
    class="number-field-input"
    inputmode="numeric"
    pattern="/d+"
    v-model="inputOne"
   />
</div>


This Question was asked in StackOverflow by Khant and Answered by Nikola Pavicevic It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?