CodexBloom - Programming Q&A Platform

Vue 3 Form Submission: How to Handle Async Validation with VeeValidate in a Complex Form?

👀 Views: 92 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-13
vue vee-validate async-validation javascript

I'm building a feature where Quick question that's been bugging me - I'm working on a complex form in a Vue 3 application using VeeValidate for form validation, but I'm struggling with how to handle asynchronous validation correctly... Specifically, I need to check if a username already exists in the database during the form submission process. When I try to perform this async check, it seems like the form doesn't wait for the validation to complete before trying to submit, which results in an empty behavior message or a failed submission without any feedback to the user. Here's a snippet of my code: ```javascript <template> <Form @submit="handleSubmit(onSubmit)"> <Field name="username" as="input" v-slot="{ field, meta }"> <input v-bind="field" placeholder="Username" /> <span>{{ meta.errors[0] }}</span> </Field> <button type="submit">Submit</button> </Form> </template> <script> import { defineComponent } from 'vue'; import { useForm, Field } from 'vee-validate'; import * as Yup from 'yup'; export default defineComponent({ setup() { const { handleSubmit } = useForm({ validationSchema: Yup.object().shape({ username: Yup.string() .required('Username is required') .test('check-username', 'Username already exists', async (value) => { const response = await fetch(`/api/check-username?username=${value}`); const data = await response.json(); return data.exists === false; }) }) }); const onSubmit = (values) => { console.log('Form Submitted:', values); }; return { handleSubmit, onSubmit }; } }); </script> ``` When I submit the form, I don't see the behavior message for the username validation, and the console log shows 'Form Submitted:' even when the username exists. I suspect that the async validation is not executing as expected. I've also tried adding `validateOnMount` and `validateOnChange`, but that didn't help. Could anyone guide me on how to properly implement this async validation so that the form submission waits for the validation to complete? I'm working on a API that needs to handle this. How would you solve this? My team is using Javascript for this REST API. Thanks for taking the time to read this!