How can I inject a $validator instance into my Vue2.7 app that uses composition api syntax

122 views Asked by At

I have a large application that is using [email protected] and [email protected]. We are in the process of transitioning to Vue@3 so we are using [email protected] to write new components with the syntax <script setup lang="ts">

In old components we call validation on form submission with this.$validator.validate(). However, $validator is not accessible in the <script setup lang="ts"> components. I have tried creating a new Validator() instance in my new components and using that but it also fails.

How can I set up my application so that the old $validator.validate() calls work and so that I can programmatically run validate in the new Vue2.7 components?

I'm assuming I need to create a validator instance and explicitly inject it but I'm struggling to figure out how: https://vuejs.org/guide/components/provide-inject.html

2

There are 2 answers

0
Programmingjoe On BEST ANSWER

After a bunch of investigation I've found my best approach is going to be to use a tool like yup for our validation and to simply not use vee-validate for any components that use vue2.7 syntax. yup is used by vee-validate v4 so if desired the upgrade to vee-validate v4 should be easier. However, we are likely going to opt for rolling our own integration between yup and vue rather than using vee-validate moving forward.

Yup docs: https://www.npmjs.com/package/yup

I used something like this to turn the yup form validation into a block of errors I can display on the form: Transform Yup validation error into a useable object

0
Mardagg On

I faced the same problem. I finally used ValidationProvider that is the new way to validate forms, and it is compatible with 2.x. Here an example :

<template>
<ValidationObserver v-slot="{ invalid, validate }">
    <ValidationProvider name="subject" rules="required" v-slot="{ errors }" slim>
        <v-text-field
            v-model="myModel"
            name="subject"
            :error="!!errors[0]"
        />
    </ValidationProvider>
    <v-btn
        :disabled="invalid"
        @click="validate().then(submit)"
    />
</ValidationObserver>
</template>

<script setup lang="ts">
const submit = async () => {
    // called when form is valid
}
</script>