react-hook-form / resolvers

📋 Validation resolvers: Yup, Zod, Superstruct, Joi, Vest, Class Validator, io-ts, Nope, computed-types, typanion, Ajv, TypeBox, ArkType, Valibot, effect-ts and VineJS
https://react-hook-form.com/
MIT License
1.74k stars 159 forks source link

[Zod]: Resolver does not validate to reflect correct error state without manual form.trigger() #671

Open MusaGillani opened 6 months ago

MusaGillani commented 6 months ago

Describe the bug Form Validation doesn't re render the correct error message to reflect correct error from formState

To Reproduce Steps to reproduce the behavior:

  1. Visit the sandbox with a minimal working example using react-hook-form bootstrapped with shadcn ui
  2. Enter a value smaller than the total value listed in UI in the Base labelled input field
  3. Click submit
  4. The error message indicates a sum mismatch
  5. Enter the remaining sum value in any other field
  6. This does not cause the error message to hide although the error state updates correctly, verified from console logs
  7. Only changing the values in Base input field remove the errors from the UI

Screen recording showing validation not running: Video

Sandbox link

Expected behavior Validation should trigger when changing a any other field than base , due to formState update causing resolver to re-validate the form data

Desktop:

Additional context The error is fixed using form.trigger() directly in the onChange of the <Input/> component, which removes the error from the UI when changing the input value. Maybe the formState is being updated correctly but the resolver does cause a re-render?

Screen Recording, showing form.trigger() added to the Overtime label triggers the validation Video

briavicenti commented 6 months ago

We're having a similar issue, described in a comment here! I think that these two issues are dupes.

sowka1995 commented 5 months ago

I have a similar issue. The refine function is triggered and resolved but error from formState.erros does not disappear -> if I call form.trigger() in every onChange field callback then everything works good and errors are cleared form formState.

sowka1995 commented 5 months ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

MusaGillani commented 5 months ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

sowka1995 commented 5 months ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

MusaGillani commented 5 months ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

sowka1995 commented 5 months ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

Maybe, but I do not think so. The problem with using trigger() is that in the case of mode="onSubmit" (default) the error will be displayed even before the form is submitted but using rules.deps, the error appears only after submit.

MusaGillani commented 5 months ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

Maybe, but I do not think so. The problem with using trigger() is that in the case of mode="onSubmit" (default) the error will be displayed even before the form is submitted but using rules.deps, the error appears only after submit.

yeah we're using submitCount from formState to only trigger() when the form is submitted once. since the entire schema needs to be validated all trigger() calls we're already running in a useEffect using watch()'s subscription. just added that check in useEffect

here's the snippet for that

  useEffect(() => {
    if (form.formState.submitCount === 0) {
      return;
    }
    const subscription = form.watch(() => form.trigger());
    return () => subscription.unsubscribe();
  }, [form.watch, form.trigger, form.formState, form]);
benjamin-andersen commented 2 weeks ago

@MusaGillani the interesting thing is that when you add rules={{ deps: ['field1', 'field2'] }} to FormField (which passthrough to Controller) it works as expected :D https://stackblitz.com/edit/stackblitz-starters-8cqgsc

Interesting, could you point me to some docs for this? would like to dig a lil deeper

I found it by accident. I was looking for something like "dependencies" because I worked with Ant Design for a very long time and there I used it a lot to solve this kind of problem. Once I found this in the rules object, I set it up, tested it and it actually works, but why isn't there anything about it in the documentation? Maybe it also works by accident :D

yeah the docs seem pretty arcane atp, i wonder if it uses trigger() under the hood, since the validations were working fine with updates to formstates as well but re-renders were not being "triggered"

Maybe, but I do not think so. The problem with using trigger() is that in the case of mode="onSubmit" (default) the error will be displayed even before the form is submitted but using rules.deps, the error appears only after submit.

yeah we're using submitCount from formState to only trigger() when the form is submitted once. since the entire schema needs to be validated all trigger() calls we're already running in a useEffect using watch()'s subscription. just added that check in useEffect

here's the snippet for that

  useEffect(() => {
    if (form.formState.submitCount === 0) {
      return;
    }
    const subscription = form.watch(() => form.trigger());
    return () => subscription.unsubscribe();
  }, [form.watch, form.trigger, form.formState, form]);

Thanks for the workaround! I was searching for a long time to find a solution to this issue...

If anyone happens to want to trigger the revalidation with a different validation strategy (e.g. "onBlur" instead of the default "onSubmit"), you can try this:

Note: I have not really fully tested this, seems fine at a glance. Use at your own risk :) Also note: This will also of course cause an extra re-render, so maybe someone else can come up with a more optimal workaround that handles it for other validation strategies.

const [hasValidated, setHasValidated] = useState(false)

// hack to enable form revalidation
// only after form has been validated for the first time
useEffect(() => {
    if (hasValidated) return
    if (!form.formState.isValidating) return
    setHasValidated(true)
}, [form.formState.isValidating, hasValidated])

// manually trigger entire form revalidation
// anytime any of the form values changes
useEffect(() => {
    if (!hasValidated) return

    const subscription = form.watch(() => form.trigger())
    return subscription.unsubscribe
}, [form.watch, form.trigger, hasValidated])

And here is a wrapper on-top of useForm with this functionality built-in:

// useFormWithRevalidate.ts
import {useEffect, useState} from 'react'
import {
    FieldValues,
    UseFormProps,
    UseFormReturn,
    useForm,
} from 'react-hook-form'

/**
 * This is a wrapper of {@link useForm}.
 *
 * It is a workaround for a bug with react-hook-form + zod resolver.
 *
 * See details: https://github.com/react-hook-form/resolvers/issues/671
 */
export const useFormWithRevalidate = <
    TFieldValues extends FieldValues = FieldValues,
    TContext = any,
    TTransformedValues extends FieldValues | undefined = undefined,
>(
    props?: UseFormProps<TFieldValues, TContext>,
): UseFormReturn<TFieldValues, TContext, TTransformedValues> => {
    const form = useForm<TFieldValues, TContext, TTransformedValues>(props)
    const [hasValidated, setHasValidated] = useState(false)

    // hack to enable form revalidation
    // only after form has been validated for the first time
    useEffect(() => {
        if (hasValidated) return
        if (!form.formState.isValidating) return
        setHasValidated(true)
    }, [form.formState.isValidating, hasValidated])

    // manually trigger entire form revalidation
    // anytime any of the form values changes
    useEffect(() => {
        if (!hasValidated) return

        const subscription = form.watch(() => form.trigger())
        return subscription.unsubscribe
    }, [form.watch, form.trigger, hasValidated])

    return form
}