CodexBloom - Programming Q&A Platform

Vue 3: Handling Conditional Form Fields with VeeValidate and Reactive State

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
vue.js vee-validate conditional-forms JavaScript

I'm working on a project and hit a roadblock. I'm working on a Vue 3 application where I need to manage a form that has conditional fields based on user selection. I'm using VeeValidate for validation, but I'm running into issues where the validation schema doesn't seem to update correctly when fields are shown or hidden. For example, I have a select dropdown that, when set to 'Yes', should display additional input fields for details, and when set to 'No', those fields should disappear. However, when I submit the form with the select set to 'No', VeeValidate still checks the hidden fields for validation, which leads to unexpected validation errors. Here’s a simplified version of my code: ```vue <template> <form @submit.prevent="handleSubmit(onSubmit)"> <select v-model="formData.option" @change="updateFields"> <option value="">Select</option> <option value="yes">Yes</option> <option value="no">No</option> </select> <div v-if="showDetails"> <input v-model="formData.details" v-validate="'required'" placeholder="Details" /> <span v-if="errors.details">{{ errors.details }}</span> </div> <button type="submit">Submit</button> </form> </template> <script> import { useForm, useField } from 'vee-validate'; import * as yup from 'yup'; export default { setup() { const { handleSubmit, errors } = useForm(); const { value: details, errorMessage: detailsError } = useField('details', yup.string().required('Details are required').when('option', { is: 'yes', then: yup.string().required() })); const formData = reactive({ option: '', details: '', }); const showDetails = computed(() => formData.option === 'yes'); return { handleSubmit, errors, formData, showDetails, details, detailsError }; }, }; </script> ``` I've tried several approaches, including adjusting the validation schema dynamically, but nothing seems to work. The hidden fields still throw errors when I submit. I'm using VeeValidate version 4.5.7 and Vue 3.2.0. How can I ensure that validation only applies to visible fields to avoid these issues? Any help would be greatly appreciated!