表单验证
On this page

表单验证

¥Form Validation

本指南将指导你在 Remix 中为一个简单注册表单实现表单验证。这里,我们专注于掌握基础知识,以帮助你理解 Remix 中表单验证的基本元素,包括 action、操作数据和渲染错误。

¥This guide walks you through implementing form validation for a simple signup form in Remix. Here, we focus on capturing the fundamentals to help you understand the essential elements of form validation in Remix, including actions, action data, and rendering errors.

步骤 1:设置注册表单

¥Step 1: Setting Up the Signup Form

我们将首先使用 Remix 的 Form 组件创建一个基本的注册表单。

¥We'll start by creating a basic signup form using the Form component from Remix.

import { Form } from "@remix-run/react";

export default function Signup() {
  return (
    <Form method="post">
      <p>
        <input type="email" name="email" />
      </p>

      <p>
        <input type="password" name="password" />
      </p>

      <button type="submit">Sign Up</button>
    </Form>
  );
}

步骤 2:定义操作

¥Step 2: Defining the Action

在此步骤中,我们将在与 Signup 组件相同的文件中定义一个服务器 action。请注意,本文旨在提供所涉及机制的概述,而不是深入研究表单验证规则或错误对象结构。我们将对电子邮件和密码进行基本的检查,以演示核心概念。

¥In this step, we'll define a server action in the same file as our Signup component. Note that the aim here is to provide a broad overview of the mechanics involved rather than digging deep into form validation rules or error object structures. We'll use rudimentary checks for the email and password to demonstrate the core concepts.

import type { ActionFunctionArgs } from "@remix-run/node"; // or cloudflare/deno
import { json, redirect } from "@remix-run/node"; // or cloudflare/deno
import { Form } from "@remix-run/react";

export default function Signup() {
  // omitted for brevity
}

export async function action({
  request,
}: ActionFunctionArgs) {
  const formData = await request.formData();
  const email = String(formData.get("email"));
  const password = String(formData.get("password"));

  const errors = {};

  if (!email.includes("@")) {
    errors.email = "Invalid email address";
  }

  if (password.length < 12) {
    errors.password =
      "Password should be at least 12 characters";
  }

  if (Object.keys(errors).length > 0) {
    return json({ errors });
  }

  // Redirect to dashboard if validation is successful
  return redirect("/dashboard");
}

如果发现任何验证错误,这些错误会从 action 返回到客户端。这是我们向 UI 发出需要更正某些内容的信号的方式;否则用户将被重定向到仪表盘。

¥If any validation errors are found, they are returned from the action to the client. This is our way of signaling to the UI that something needs to be corrected; otherwise the user will be redirected to the dashboard.

步骤 3:显示验证错误

¥Step 3: Displaying Validation Errors

最后,我们将修改 Signup 组件以显示验证错误(如果有)。我们将使用 useActionData 来访问和显示这些错误。

¥Finally, we'll modify the Signup component to display validation errors, if any. We'll use useActionData to access and display these errors.

import type { ActionFunctionArgs } from "@remix-run/node"; // or cloudflare/deno
import { json, redirect } from "@remix-run/node"; // or cloudflare/deno
import { Form, useActionData } from "@remix-run/react";

export default function Signup() {
  const actionData = useActionData<typeof action>();

  return (
    <Form method="post">
      <p>
        <input type="email" name="email" />
        {actionData?.errors?.email ? (
          <em>{actionData?.errors.email}</em>
        ) : null}
      </p>

      <p>
        <input type="password" name="password" />
        {actionData?.errors?.password ? (
          <em>{actionData?.errors.password}</em>
        ) : null}
      </p>

      <button type="submit">Sign Up</button>
    </Form>
  );
}

export async function action({
  request,
}: ActionFunctionArgs) {
  // omitted for brevity
}

结论

¥Conclusion

就这样!你已成功在 Remix 中设置基本表单验证流程。这种方法的优点在于,错误会根据 action 数据自动显示,并且在用户每次重新提交表单时都会更新。这减少了你需要编写的样板代码量,从而使你的开发过程更加高效。

¥And there you have it! You've successfully set up a basic form validation flow in Remix. The beauty of this approach is that the errors will automatically display based on the action data, and they will be updated each time the user re-submits the form. This reduces the amount of boilerplate code you have to write, making your development process more efficient.

Remix v2.17 中文网 - 粤ICP备13048890号