【问题标题】:How to properly add custom validation to array in vuelidate如何正确地将自定义验证添加到 vuelidate 中的数组
【发布时间】:2019-07-09 02:20:32
【问题描述】:

我有一个具有以下结构的对象数组

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
        }
      }
    }
  }
}
},

【问题讨论】:

  • 在模板中使用$each[index]
  • 嗨@ChristhoferNatalius 感谢您的回复!你这是什么意思?
  • 我在这里找到了官方指南:vuelidate.js.org/#sub-collections-validation。应该适合你的情况,先看看吧。

标签: javascript vue.js vuelidate


【解决方案1】:

应该是这样的。

<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>

更改错误类别以满足您的需要。

【讨论】:

    【解决方案2】:

    我有完全相同的需求,发现解决方案非常简单,一旦你把你的头脑围绕着你正在尝试做的事情。仅当当前项与任何以前的项重复时,您的验证器才需要触发。

    类似这样的:

    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 }
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-03
      • 1970-01-01
      • 2020-01-07
      • 2019-08-16
      相关资源
      最近更新 更多