vuelidate
vuelidate copied to clipboard
Avoid data duplication in a collection
Is there an simple way?
Please give a better explanation to your issue.
I'm using oficial sample to illustrate my doubt. https://vuelidate.netlify.com/#sub-collections-validation The question is, how avoid repeated items in a collection, like individual names.
You want to validate whether an array has repeating items? If so, then a custom validator function would be best
If this is resolved, please close the ticket.
Hi. I know this is an old issue but this is the first result when I searched about data duplication in collections.
To solve this, you can create a custom validator like this:
export const unique = (group, key) => {
return (value) => {
const found = group.filter(item => {
if (key) {
return item[key] == value;
}
return item == value;
});
return found.length <= 1;
};
}
Now, in your component:
...
validations () {
return {
candies: {
unique: unique(this.candies),
},
cookies: {
$each: {
name: {
unique: unique(this.cookies, 'name'), // for array of objects
},
},
},
};
},
...
This solution is fine and works, but it can be improved. The downsides are:
- You have to pass the array where the property belongs.
- If it's an array of objects, you have to pass the key of the property.
I wanted to solve this but I haven't found anything in the docs.