vee-validate icon indicating copy to clipboard operation
vee-validate copied to clipboard

Dynamic fields still required after removing on submit - `useFormContext()` and `destroyPath()` best practice?

Open borsTiHD opened this issue 10 months ago • 0 comments

What happened?

My problem is a little hard to explain.
I have a static form with a few dynamic fields, that could be added depending on a remote json file. In addition, each field comes with its own validation rules and some fields are hidden or removed depending on the state of other fields (e.g. checkbox and a v-if).

Now I have two problems.

  1. In the devtools the fields in the form count up to infinity as soon as I change states that show/hide fields. Although the "shown" fields correspond to those that are still visible. For example, there are 4 fields, but by constantly showing/hiding them, the devtools show 30 fields.
  2. If a field that was "required" was hidden (e.g. by a state change), I have the problem that when the form is submitted, the non-existent field ensures that the form is not valid.

After a lot of trial and error I came across useFormContext and from there destroyPath. I use individual input fields in child components and call destroyPath(fieldName) in an onUnmounted hook.
With destroyPath the fields disappear correctly and no longer generate validation errors. This solves my problem. 😁👍

Since I couldn't find anything about this in the docs, I wanted to ask, is my way "best practice", or is there another way to solve my problem? And how safe is it to use destroyPath?

Thank you in advance

Reproduction steps

Difficult, but something like this:

  1. Create a form with static fields with "useForm()" but no schema
  2. Each field will be registered by an child component -> useField(name, schema) name is a ref
  3. Create additional fields async with a v-for loop -> also by child components with useField(name, schema)
  4. For example change the state from a checkbox (boolean) and control another field by v-if

Version

Vue.js 3.x and vee-validate 4.x

What browsers are you seeing the problem on?

  • [ ] Firefox
  • [X] Chrome
  • [ ] Safari
  • [ ] Microsoft Edge

Relevant log output

Even if I don't see any validation errors in the devtools, I get validation errors when submitting the form:

handleSubmit(async (values) => { ... }, onInvalidSubmit({ values, errors, results }: InvalidSubmitEvent) { ... }))

// "errors" gets the validation errors from removed fields and the form cannot be sent  
// even if the fields no longer exist in the devtools

Demo link

na

Code of Conduct

  • [X] I agree to follow this project's Code of Conduct

borsTiHD avatar Dec 02 '24 14:12 borsTiHD