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
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;
}
}
}
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
}
},
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.