使用 React Hook Form + Zod 构建表单

介绍

当我开始编程时,我需要用纯 javascript 编写大量代码来从表单收集数据。从那时起,web 开发已经发展得如此之快,以至于今天我们有了抽象了大部分工作的库,从而促进了表单数据的管理。

在本文中,我将向您展示如何使用 react hook form 来处理表单数据,并使用 zod 以高效且有组织的方式验证这些数据。

我很着急,请给我完整的代码

它在你手里:

import { label } from '@/components/ui/label';
import { input } from '@/components/ui/input';
import { button } from '@/components/ui/button';
import { gamepad, gamepad2 } from 'lucide-react';
import { useform } from 'react-hook-form';
import { z } from 'zod';
import { zodresolver } from '@hookform/resolvers/zod';
import { toast, toaster } from 'sonner';

const signupform = z
  .object({
    name: z
      .string()
      .min(2, { message: 'nome deve ter ao menos 2 caracteres' })
      .max(50, { message: 'nome deve ter no máximo 50 caracteres' }),
    email: z.string().email().max(100, { message: 'e-mail deve ter no máximo 100 caracteres' }),
    password: z.string().max(100, { message: 'senha deve ter no máximo 100 caracteres' }),
    confirm: z.string(),
  })
  .refine((data) => data.password === data.confirm, {
    message: 'senhas não conferem!',
    path: ['confirm'],
  });

type signupform = z.infer<typeof signupform>;

export function app() {
  const {
    handlesubmit,
    register,
    reset,
    formstate: { issubmitting, errors },
  } = useform<signupform>({
    resolver: zodresolver(signupform),
  });

  async function handlesignup(data: signupform) {
    console.log(data);
    await new promise((resolve) => {
      settimeout(resolve, 2000);
    });
    reset();
    toast.success('conta criada com sucesso!');
  }

  return (
    <>
      <toaster richcolors />
      <div classname="min-h-screen lg:grid lg:grid-cols-2 antialiased gap-8">
        <div classname="hidden lg:flex h-full justify-center border-r border-foreground/5 bg-foreground text-muted-foreground items-center gap-3 text-lg">
          <gamepad2 />
          <span classname="font-semibold">gamers.shop</span>
        </div>
        <div classname="flex flex-col items-center justify-center gap-6 min-h-screen">
          <div classname="px-10 w-96 h-full flex flex-col justify-center items-center lg:w-[500px]">
            <h1 classname="flex items-center gap-2 mb-4 text-2xl font-semibold tracking-tight">
              <gamepad />
              crie sua conta
              <gamepad />
            </h1>
            <form onsubmit={handlesubmit(handlesignup)} classname="space-y-4 w-full ">
              <div classname="space-y-2">
                <label htmlfor="name">nome</label>
                <input id="name" type="text" {...register('name')} />
                {errors.name && <span classname="text-sm text-red-500">{errors.name.message}</span>}
                {}
              </div>
              <div classname="space-y-2">
                <label htmlfor="email">email</label>
                <input id="email" type="email" {...register('email')} />
                {errors.email && <span classname="text-sm text-red-500">{errors.email.message}</span>}
              </div>
              <div classname="space-y-2">
                <label htmlfor="password">senha</label>
                <input id="password" type="password" {...register('password')} />
                {errors.password && <span classname="text-sm text-red-500">{errors.password.message}</span>}
              </div>
              <div classname="space-y-2">
                <label htmlfor="confirm">confirme a senha</label>
                <input id="confirm" type="password" {...register('confirm')} />
                {errors.confirm && <span classname="text-sm text-red-500">{errors.confirm.message}</span>}
              </div>

              <button classname="w-full" type="submit" disabled={issubmitting}>
                criar conta
              </button>
            </form>
          </div>
        </div>
      </div>
    </>
  );
}

教程

构建表格

首先,我创建了一个包含四个字段的表单:姓名、电子邮件、密码和密码确认。为了方便接口的开发,我使用了shadcn、tailwind和lucide-react。使用 css 类可能看起来有点冗长,但它们有助于保持一致的设计。

<form classname="space-y-4 w-full ">
  <div classname="space-y-2">
    <label htmlfor="name">nome</label>
    <input id="name" type="text" placeholder="digite o seu nome"/>
  </div>
  <div classname="space-y-2">
    <label htmlfor="email">email</label>
    <input id="email" type="email" placeholder="digite o seu e-mail"/>
  </div>
  <div classname="space-y-2">
    <label htmlfor="password">senha</label>
    <input id="password" type="password" placeholder="digite uma senha"/>
  </div>
  <div classname="space-y-2">
    <label htmlfor="confirm">confirme a senha</label>
    <input id="confirm" type="password" placeholder="digite a senha novamente"/>
  </div>

  <button classname="w-full" type="submit">
    criar conta
  </button>
</form>

我在此表单中创建了 4 个字段:姓名、电子邮件、密码和确认。我需要以某种方式验证它们。由于此示例用于解释 zod 的使用,因此我避免使用本机 html 属性(必需、最大长度等)。

使用 zod 进行数据验证

为了确保在字段中输入的数据正确,我使用 zod 创建了一个验证模式。该架构定义了每个字段的限制并自定义错误消息:

import { z } from 'zod';

const signupformschema = z
  .object({
    name: z
      .string()
      .min(2, { message: 'nome deve ter ao menos 2 caracteres' })
      .max(50, { message: 'nome deve ter no máximo 50 caracteres' }),
    email: z.string().email().max(100, { message: 'e-mail deve ter no máximo 100 caracteres' }),
    password: z.string().max(100, { message: 'senha deve ter no máximo 100 caracteres' }),
    confirm: z.string(),
  })
  .refine((data) => data.password === data.confirm, {
    message: 'senhas não conferem!',
    path: ['confirm'],
  });

此架构定义了每个字段所需的类型和验证。使用 .refine() 方法来确保“密码”和“确认”字段中输入的密码相同。

.refine((data) => data.password === data.confirm, {
  message: 'senhas não conferem!',
  path: ['confirm'],
});

与 react hook form 和 zod resolver 集成

react hook form 是一个表单库,它通过减少不必要的重新渲染和简化数据操作来提高性能。我使用 useform() 来配置表单,通过 zodresolver 传递验证架构:

import { zodresolver } from '@hookform/resolvers/zod';
import { useform } from 'react-hook-form';

type signupform = z.infer<typeof signupformschema>;

const {
    handlesubmit,
    register,
    reset,
    formstate: { issubmitting, errors },
  } = useform<signupform>({
    resolver: zodresolver(signupformschema),
  });

我在 useform() 中使用的函数和变量是:

  • handlesubmit:处理表单提交。
  • register:将表单字段绑定到react hook form数据管理。
  • 重置:重置表单。
  • issubmitting:表示表单是否正在提交。
  • 错误:存储每个字段的验证错误。 ### 表单提交功能 为了模拟表单提交,我创建了handlesignup函数,它添加了一个等待时间来查看issubmitting状态并用toast显示成功消息:
async function handlesignup(data: signupform) {
  console.log(data);
  await new promise((resolve) => {
    settimeout(resolve, 2000);
  });
  reset();
  toast.success('conta criada com sucesso!');
}

然后我将函数添加到表单中:

<form onsubmit={handlesubmit(handlesignup)} classname="space-y-4 w-full">

最后,我使用寄存器来命名哪个字段属于哪个属性,并显示错误(如果存在):

<div className="space-y-2">
  <Label htmlFor="name">Nome</Label>
  <Input id="name" type="text" {...register('name')} placeholder="Digite o seu nome" />
  {errors.name && <span className="text-sm text-red-500">{errors.name.message}</span>}
</div>

结果如下所示:

使用 React Hook Form + Zod 构建表单

最后的考虑因素

在本文中,我展示了一种集成 react hook form 和 zod 来验证不受控制的表单的简单方法。该库还可以使用受控组件,因此请查阅文档以探索更多选项。

以上就是使用 React Hook Form + Zod 构建表单的详细内容,更多请关注其它相关文章!