Answer the question
In order to leave comments, you need to log in
How to validate an input with type number Vue.js?
I don’t understand how to write a check for the entered value so that it is impossible to enter the number <1 and >99. Everything that I wrote before does not work.
<input
class="qty__input form__input"
type="number"
@input="validateInputData(product.qty)"
v-model="product.qty">
<script>
methods: {
validateInputData(qty) {
// this.$emit("validateInputData")
if (qty < 1 || qty === "" || qty === 0) {
qty = 1;
}
else if (qty >= 99) {
qty = 99;
}
else {
qty = qty;
}
}
</script>
Answer the question
In order to leave comments, you need to log in
What is product?
If it's a single object, then it's easiest to set a watch on the property you're interested in:
watch: {
'product.qty'(val) {
this.product.qty = Math.max(1, Math.min(99, val | 0));
},
},
v-for
and it's an array element, then you can deep watch the entire array:watch: {
products: {
deep: true,
handler: val => val.forEach(n => n.qty = Math.max(1, Math.min(99, n.qty | 0))),
},
},
methods: {
onInput(e) {
if (e.isTrusted) {
e.target.value = Math.max(1, Math.min(99, e.target.value | 0));
e.target.dispatchEvent(new Event('input'));
}
},
},
<input
@input="onInput"
...
function onInput({ isTrusted, target: t }) {
if (isTrusted) {
t.value = Math.max(t.min, Math.min(t.max, t.value | 0));
t.dispatchEvent(new Event('input'));
}
}
const minmaxDirective = {
mounted: el => el.addEventListener('input', onInput),
unbind: el => el.removeEventListener('input', onInput),
};
app.directive('minmax', minmaxDirective);
<input
v-minmax
min="1"
max="99"
...
<template>
<input type="number" min=1 max=5 :class="{invalid:userChoice < 1 || userChoice > 5}" v-model="userChoice" />
</template>
<script>
export default {
data() {
return {
userChoice: 1
}
}
}
</script>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question