[Vuejs]-How can i set my v-text-field to not show negative numbers?

3๐Ÿ‘

You code should work.

Itโ€™s working to me.

By the way, if itโ€™s not work then you can use oninput

For your given example:

<v-text-field
   v-model="portata.quantita_portata"
   type="number"
   oninput="if(this.value < 0) this.value = 0;"
></v-text-field>

1๐Ÿ‘

If it is a quantity field, round off the value just in case.

<v-text-field
  class="mr-0 pt-0"
  hide-details
  single-line
  type="number"
  style="max-width: 60px; "
  v-model="portata.quantita_portata"
  @change="changeQuantity"
></v-text-field>

And method:

changeQuantity (qty) {
  const val = Math.round(Number(qty))
  let quantity = val
  if (val <= 0) {
    quantity = 0
  }
  this.portata.quantita_portata = quantity
}
๐Ÿ‘คAdam Szeptucho

1๐Ÿ‘

This might not be the optimal solution, but it solved my problem and may do yours as well.
I personally used a key to re-render my element. If you do not use the key it still works, but when you change the range by v-text-field itself, it will ignore the condition and negative numbers are still typeable.
Here a piece of my code:

 <v-text-field
      v-model="form.storyboard_reject_count"
      :label="$tr('storyboard_reject_count')"
          :type="'number'"
          @input="validateNegativeNumber('src_key', 
            'storyboard_reject_count')"
          :key="src_key"
        />



 validateNegativeNumber(key, value){
      if(this.form[value] < 0){
        this.form[value] = 0;
        this[key]++;
        return;
     }
 },

0๐Ÿ‘

You can add watcher:

watch: {
  'portata.quantita_portata': {
     handler: function (after, before) {
        // Changes detected.
        if(after < 0)
        {
            this.portata.quantita_portata = 0;
           // this.portata.quantita_portata = before; // can do this
        }
     },
     deep: true
  }
}
๐Ÿ‘คxxramm

Leave a comment