验证字符串的深层嵌套数组

问题描述 投票:0回答:1

我的Vue文件中具有以下结构的数据:

data() {
  return {
    formData: {
      name: 'foo',
      objects: [
        {id: 0, name: 'a', props: []},
        {id: 1, name: 'b', props: ['2', '23']},
        {id: 2, name: 'c', props: ['44']},
        {id: 3, name: 'd', props: []}
      ]
    },
    currentObj = null,
    currentPropIndex = null
  }
}

objects数组中的对象数是动态的,props数组也是动态的,可以在其中添加和删除字符串值。我需要使用Vuelidate来验证更改后每个对象中props数组的每个值。所以我尝试了这个:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      props: {
        $each: {
          required, numeric, maxLength: maxLength(5)
        }
      }
    }
  }
},

计算:

propsErrors() {
    const errors = [];
    if ( this.currentObj) {
      // const objIndex = _.findIndex(this.formData.objects, o => o.id === this.currentObj.id)
      if (!this.$v.formData.objects['props'][this.currentPropIndex].$dirty) {
        return errors;
      }
      !this.$v.formData.objects['props'][this.currentPropIndex].maxLength && errors.push('Max 5 digits')
      !this.$v.formData.objects['props'][this.currentPropIndex].required && errors.push('Required')
      !this.$v.formData.objects['props'][this.currentPropIndex].numeric && errors.push('Digits only')
    }
    return errors
  },

还有我的Vuetify文本字段:

<v-text-field single-line flat dense required
  v-model="object.props[index]"
  :error-messages="propsErrors"
  label="Prop"
  height="30"
  @click="setCurrents(protocol, index)"
  @blur="$v.formData.protocolPorts['manual_ports'][index].$touch()"
  @input="$v.formData.protocolPorts['manual_ports'][index].$touch()" />

[setCurrents仅设置当前编辑的对象和属性索引:

setCurrents (protocol, index) {
    this.currentObj = protocol;
    this.currentPropIndex = index;
  }

一旦测试页面并单击文本字段,我将收到此错误:Error in render: "TypeError: Cannot read property 'props' of undefined"

我尝试更改propsErrors(上面代码中的objIndex当前已注释掉)

this.$v.formData.objects[objIndex]['props'][index].maxLength && errors.push('Max 5 digits')

文本字段(oi代表对象索引):

@input="$v.formData.objects[oi].props[index].$touch()"

和验证:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      required,
      $each: {
        props: {
          $each: {
            required, numeric, maxLength: maxLength(5)
          }
        }
      }
    }
  }
},

仍然不断出错。有什么想法吗?

javascript validation vue.js vuelidate
1个回答
0
投票

我从没使用过Vuelidate,但我发现此示例非常有用,并且与您尝试执行的操作https://vuelidate.js.org/#sub-collections-validation相当类似>

© www.soinside.com 2019 - 2024. All rights reserved.