Search code examples
vue.jsvuejs2vue-componentvuelidate

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


I am new to Vue Js and Vuelidate. Just tried to validate form input fields from a parent component like here: https://github.com/monterail/vuelidate/issues/333

Child component in the parent:

<contact-list ref="contactList" :contacts="contacts" @primaryChanged="setPrimary" @remove="removeContact" @ready="isReady => readyToSubmit = isReady"/>

The method in the child:

computed: {
    ready() {
        return !this.$v.email.$invalid;
    }
},
watch: {
    ready(val) {
        this.$emit('ready', val);
    }
},

methods: {
    touch() {
        this.$v.email.$touch();
    }
}

I'm calling the touch() method from the parent like so:

submit() {
            this.$refs.contactList.touch();
        },

But I get this error:

Error in event handler for "click": "TypeError: this.$refs.contactList.touch is not a function".

Any ideas? Thanks.


Solution

  • 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())
    ...