Validate form input fields in child component from a parent component with Vuelidate

隐身守侯 提交于 2019-12-08 09:13:27

I have found another solution for this validation, it's very simple. Child component in the parent:

<contact-list ref="customerContacts" :contacts="customer.contacts" />

Validations in child component:

:validator="$v.model.$each[index].name
...
validations: {
    model: {
        required,
        $each: {
            name: {
                required
            },
            email: {
                required,
                email
            },
            phone: {
                required
            }
        }

    }

}

And on submit in the parent:

async onSubmit() {
            if(this.$refs.customerContacts.valid())
...

Had a similar issue trying to validate child components during a form submission on the parent component. My child components are only one level deep so if you have deeper nesting this way may not work or you have to check recursively or something. There are probably better ways to check but this worked for me. Good luck.

// parent component
  methods: {
    onSave() {
      let formIsInvalid = this.$children.some(comp => {
        if (comp.$v) { // make sure the child has a validations prop
          return comp.$v.$invalid
        }
      })

      if (!formIsInvalid) {          
        // submit data
      }          
      else {
        // handle invalid form
      }
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!