CodexBloom - Programming Q&A Platform

Vue 3: implementing Dynamic Validation Rules in a Reactive Form when Using Vuelidate

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-10
vue.js vuelidate form-validation JavaScript

I'm integrating two systems and After trying multiple solutions online, I still can't figure this out. I'm working on a Vue 3 application where I'm using Vuelidate for form validation, and I'm working with unexpected behavior with dynamic validation rules. My form has an input field that should have different validation rules based on the user's selection from a dropdown menu. For example, if the user selects 'A', the field should require a minimum length of 5 characters, but if they select 'B', it should accept any non-empty string. I've tried implementing this dynamically, but my validations don't seem to update correctly when the selection changes. Here's a simplified version of my code: ```javascript <template> <div> <select v-model="selectedOption"> <option value="A">Option A</option> <option value="B">Option B</option> </select> <input v-model="inputValue" /> <span v-if="$v.inputValue.$invalid">Invalid input</span> </div> </template> <script> import { required, minLength } from '@vuelidate/validators'; import useVuelidate from '@vuelidate/core'; export default { data() { return { selectedOption: 'A', inputValue: '', }; }, validations() { return { inputValue: { required, ...(this.selectedOption === 'A' ? { minLength: minLength(5) } : {}), }, }; }, watch: { selectedOption() { this.$v.inputValue.$reset(); // Reset validation state }, }, setup() { return useVuelidate(); }, }; </script> ``` When I change the selected option, the validation logic is not reflecting the correct rules. I see the following behavior message when submitting the form: ``` Validation failed: Input must have a minimum length of 5 characters. ``` I've confirmed that the `validations` function is being re-evaluated because I can see the validation object change when I log it. However, the behavior messages don't update accordingly. I've tried using `$reset()` on the validation state, but it hasn't resolved the scenario. Is there something I'm missing, or is there a best practice when dynamically changing validation rules in Vuelidate with Vue 3? Any help would be appreciated! I'm working on a web app that needs to handle this. What am I doing wrong? Thanks for any help you can provide!