Javascript 如何在vuelidate中将自定义验证正确添加到数组
我有一个具有以下结构的对象数组Javascript 如何在vuelidate中将自定义验证正确添加到数组,javascript,vue.js,vuelidate,Javascript,Vue.js,Vuelidate,我有一个具有以下结构的对象数组 varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] 我创建了一个名为isDuplicate的自定义验证,它检查属性“type”的重复值。比如说 varientSections: [ { type: "
varientSections: [
{
type: "",
values: [
{
varientId: 0,
individualValue: ""
}
]
}
]
我创建了一个名为isDuplicate的自定义验证,它检查属性“type”的重复值。比如说
varientSections: [
{
type: "Basket",
values: [
{
varientId: 0,
individualValue: ""
}
]
},
{
type: "Basket", // ERROR: Duplicate with the "above" object
values: [
{
varientId: 1,
individualValue: ""
}
]
}
],
我能够让我的自定义验证工作。但是,对于数组中存在的所有对象,$invalid属性将为false。因此,阵列中的所有对象都将以红色亮显
下面是我的验证代码:
validations: {
varientSections: {
$each: {
type: {
required,
isDuplicate(type, varient) {
console.log(varient);
const varientIndex = this.varientSections.findIndex(
v => v.type === type
);
var isWrong = true;
this.varientSections.forEach((varObject, index) => {
if (index !== varientIndex) {
if (varObject.type === varient.type) {
isWrong = false;
}
}
});
return isWrong;
}
},
values: {
$each: {
individualValue: {
required
}
}
}
}
}
},
应该是这样的
<div v-for="(vs, index) in varientSections" :key="index">
<input :class="{'is-error': $v.varientSections.$each[index].type.$error}" type="text" v-model="vs.type">
<input :class="{'is-error': $v.varientSections.$each[index].value.$error}" type="text" v-model="vs.value>
</div>
我也有同样的需求,并且发现只要你把你的头脑集中在你想做的事情上,解决方案就相当简单了。仅当当前项与以前的任何项重复时,您的验证器才需要触发
大概是这样的:
validations: {
varientSections: {
$each: {
isUnique(currItem, itemArr) {
// Find the index of the first item in the array that has the same type
var firstIdx = itemArr.findIndex((item /*, index, arr*/) => currItem.type === item.type );
// If it's the same as the current item then it is not a duplicte
if(currItem === itemArr[firstIdx])
return true;
// All others are considered duplicates
return false;
},
type: { required }
}
}
}
在templateHi@ChristhoferNatalius中使用$each[index]
,谢谢您的回复!你这是什么意思?我在这里找到了官方指南:。应该适合你的情况,先看看。