There's a form where fields are dynamically added on a click event. I want a validation error to appear when the field value is less than 9 digits after changing or blurring it. The issue is that since the fields are created dynamically with the same v-model, the rule applies to all of them. How can I make it so that it only affects the one the user is currently interacting with? Initially, the screen loads with 10 fields, and more can be added later. While filling out the first 10 fields, I don't want a validation message to pop up after the 5th one fails, affecting all subsequent fields.
Below is a simplified version of the code:
<template>
<div>
<div>
<button @click="onAddBarcodes">Add More</button>
</div>
<div v-for="(barcode, index) in barcodes" :key="index">
<div>
<div>
<label>Starting Roll #:</label>
<input
name="startbarcoderoll"
maxlength="9"
v-model.trim="$v.barcode.barcodeStart.$model"
:id="barcode.id"
ref="bcentry"
/>
<!-- max length message -->
<div v-if="!$v.barcode.barcodeStart.minLength">
<span
v-if="!$v.barcode.barcodeStart.minLength"
>App Barcode must be exactly {{$v.barcode.barcodeStart.$params.minLength.min}} characters.</span>
</div>
</div>
<button @click="onDeleteBarcodes(barcode.id)">Remove</button>
</div>
</div>
</div>
</template>
<script>
const { minLength } = require("vuelidate/lib/validators");
export default {
data() {
return {
barcodes: [],
barcode: {
barcodeStart: ""
}
};
},
validations: {
barcode: {
barcodeStart: {
minLength: minLength(9)
}
}
},
methods: {
scanBarcodeNumber(value) {
this.barcode.barcodeStart = value;
this.$v.barcode.barcodeStart.$touch();
},
onAddBarcodes() {
const newBarcode = {
id: Math.random() * Math.random() * 1000,
barcodeStart: ""
};
this.barcodes.push(newBarcode);
},
onDeleteBarcodes(id) {
this.barcodes = this.barcodes.filter(barcode => barcode.id !== id);
}
}
};
</script>
Here's a visual illustration of the problem:
Note: Vuelidate is installed globally within Vue for use across multiple components, which explains why it's not directly featured in this specific code snippet.
https://i.stack.imgur.com/ROZjE.png https://i.stack.imgur.com/xdOPD.png