2

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

Community
  • 1
  • 1
S Panfilov
  • 16,641
  • 17
  • 74
  • 96

2 Answers2

6

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;
    } else if (value < 0 || Number.isNaN(value)) {
      this.model = 0;
    } else {
      this.model = value;
    }
  }
}
nik_m
  • 11,825
  • 4
  • 43
  • 57
Linus Borg
  • 23,622
  • 7
  • 63
  • 50
2

I use Vue Validator for those cases, sample JSFiddle here:

HTML:

<div id="app">
  <pre>{{$testValidator | json}}</pre>
  <validator name="testValidator">
    <form v-on:submit.prevent="submitForm" novalidate>
      <input type="number" v-model="value" v-validate:value="{min:1, max:10}"/>
      <span class="help-block" v-show="$testValidator.value.max || $testValidator.value.min">Please enter a number between 1 and 10.</span>
      <br/>
      <button type="submit">Submit</button>
    </form>
  </validator>
</div>

JS:

new Vue({
  el: "#app",
  data: {
    value: 1
  },
  methods: {
    submitForm: function() {
      this.$validate(true);
      if (this.$testValidator.valid) {
        // do other stuff here
      }
    },
  }
});
Gus
  • 4,437
  • 2
  • 24
  • 27