React Hook Form: useForm在formState中没有返回任何错误。

huangapple go评论84阅读模式
英文:

React Hook Form: useForm not returning any errors in formState

问题

我正在使用T3堆栈 + react-hook-form + zodResolver:@hookform/resolvers/zod创建一个应用程序。

我有一个如下定义的zod模式:

export const AccountSchema = z.object({
  id: z.string().uuid().optional(),
  title: z.string().min(1, { message: 'Title is required' }),
  description: z.string().min(1, { message: 'Description is required' }),
});

export type Account = z.infer<typeof AccountSchema>;

在组件中,我正在使用useForm Hook,如下所示:

const editForm = useForm<Account>({ resolver: async (val, ctx, opt) => {
    const res = await zodResolver(AccountSchema)(val, ctx, opt);
    console.log('Validation Result:', res, val);
    return zodResolver(AccountSchema)(val, ctx, opt);
  }});

表单提交处理程序:

onSubmit={void editForm.handleSubmit(() => console.log('success'), (val) => console.log('Errors: ', val))}

使用的包:

  • "zod" -> "3.20.7"
  • "@hookform/resolvers" -> "2.9.11"
  • "react-hook-form" -> "7.43.5"

问题:
查看控制台日志,我可以看到zodResolver将正确的错误传递给useForm解析器,但formState对象中的errors始终为undefined,即editForm.formState.errors.title始终返回undefined。
此外,无论表单是有效还是无效,都会在提交时重新加载页面。

英文:

I am creating a app using T3 stack + react-hook-form + zodResolver:@hookform/resolvers/zod

I have a zod schema defined as below

export const AccountSchema = z.object({
  id: z.string().uuid().optional(),
  title: z.string().min(1, { message: &#39;Title is required&#39; }),
  description: z.string().min(1, { message: &#39;Description is required&#39; }),
});

export type Account = z.infer&lt;typeof AccountSchema&gt;;

And in a component I am making use of useForm Hook as below

const editForm = useForm&lt;Account&gt;({ resolver: async (val, ctx, opt) =&gt; {
    const res = await zodResolver(AccountSchema)(val, ctx, opt);
    console.log(&#39;Validation Result: &#39;, res, val);
    return zodResolver(AccountSchema)(val, ctx, opt);
  }});

form Submit Handler:

onSubmit={void editForm.handleSubmit(() =&gt; console.log(&#39;success&#39;), (val) =&gt; console.log(&#39;Errors: &#39;, val))}

Packages used:

&quot;zod&quot; -&gt; &quot;3.20.7&quot;
&quot;@hookform/resolvers&quot; -&gt; &quot;2.9.11&quot;
&quot;react-hook-form&quot; -&gt; &quot;7.43.5&quot;

Issue:
Looking at the console log, I can see zodResolver is passing correct errors to useForm resolver but in the formState object errors is always undefined
ie: editForm.formState.errors.title is always returning as undefined.
Also on submit always reloads the page irrespective of the form being valid or invalid.

答案1

得分: 0

以下是代码部分的中文翻译:

好吧,刚刚发生在我身上,结果是我在表单字段中调用了错误的onSubmit操作:

const schema = z.object({
  description: z.string().min(3).max(50).nonempty(),
  amount: z.number().min(0).nonnegative(),
  category: z.enum(categories),
});    

type FormData = z.infer<typeof schema>;
    
const DataForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm<FormData>({ resolver: zodResolver(schema) });

然后,更改表单的onSubmit解决了问题:

<form onSubmit={handleSubmit()}>

希望这对你有所帮助。

英文:

Well, it just happened to me and turned out that I'm calling the wrong onSubmit action in the form field:

const schema = z.object({
  description: z.string().min(3).max(50).nonempty(),
  amount: z.number().min(0).nonnegative(),
  category: z.enum(categories),
});    

type FormData = z.infer&lt;typeof schema&gt;;
    
    const DataForm = () =&gt; {
      const {
        register,
        handleSubmit,
        formState: { errors },
      } = useForm&lt;FormData&gt;({ resolver: zodResolver(schema) });

Then, changing the form onSubmit solved the issue:

&lt;form onSubmit={handleSubmit()}&gt;

Hope this helps out.

答案2

得分: 0

"Wow."
"The 'void' before handleSubmit was causing the issue."
"Had added void due to eslint@typescript-eslint/no-misused-promises rule."

英文:

Wow.
The "void" before handleSubmit was causing the issue.
Had added void due to eslint@typescript-eslint/no-misused-promises rule.

huangapple
  • 本文由 发表于 2023年3月8日 18:19:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定