Sergey Panfilov Sergey Panfilov - 4 months ago 27
Javascript Question

How to add constraints to v-model

In terms of vuejs:

How to add constraints(limits) to

v-model
properly?
Let's say I want to allow only numbers between
0
and
5
.

<input type="number" v-model="model"/>


Perhaps I can
watch
input's value. But it's a bit hacky, isn't it?

UPD: Other option is to handle
onChange
,
onKeyUp
and etc and other events: HTML Text Input allow only Numeric input

Answer

Don't abuse watch for this. use a binding and an event method:

<input type="number" v-bind:value="model" @input="handleInput"/>

JS:

methods: {
  handleInput: function(event) {
    var value = Number(event.target.value)
    if (value > 5) {
      this.model = 5
    }
    elseif (value < 0 || Number.isNaN(value)) {
      this.model = 0
    }
    else
      this.model = value
    }
  }
}
Comments