Home > Blockchain >  How to limit a max number for a NUMBER input in vue?
How to limit a max number for a NUMBER input in vue?

Time:09-20

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"
    
    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"
        
        inputmode="numeric"
        pattern="/d "
        v-model="inputOne"
   />

CodePudding user response:

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"
    
    inputmode="numeric"
    pattern="/d "
    v-model="inputOne"
   />
</div>

CodePudding user response:

You can simply achieve that by single line of code with the help of @input event.

Live Demo :

new Vue({
  el: '#app',
  data: {
    value: 0
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="number" v-model="value" @input="() => { if(value > 150 || value < 0) { value = 150 }}">
</div>

  • Related