Gianmaria Vinci
Gianmaria Vinci

Reputation: 25

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

I need to exclude negative numbers from my <v-text-field> is there any props or a way to do it?

Here is it:

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

Upvotes: 0

Views: 6299

Answers (4)

Ahmad Reza Azimi
Ahmad Reza Azimi

Reputation: 582

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;
     }
 },

Upvotes: 1

Adam Szeptucho
Adam Szeptucho

Reputation: 42

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
}

Upvotes: 1

Mr. Perfectionist
Mr. Perfectionist

Reputation: 2746

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>

Upvotes: 4

xxramm
xxramm

Reputation: 149

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
  }
}

Upvotes: 0

Related Questions