Skip to content

表单使用 Validation

中等 约 30 分钟

你将构建什么

registration 表单使用 email and 密码字段那个验证 in 真实时间. Shows 错误消息 for 无效输入 and 成功消息 on 有效 submission.

学习目标

  • 构建 controlled 表单输入
  • 验证输入 in 真实时间 as 用户类型
  • Prevent 表单 submission 使用无效数据
  • Show and 清晰错误消息

前置要求

  • Controlled 组件
  • 事件 handling
  • Conditional 渲染

步骤

  1. 1

    设置表单状态

    创建状态 for email, 密码, and 错误对象.

    代码
    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");
    const [errors, setErrors] = useState({});

    预期结果

    表单状态是 ready.

  2. 2

    添加 validation 函数

    创建验证函数那个检查 email 格式 and 密码长度, returning 错误对象.

    代码
    const validate = () => {
      const errs = {};
      if (!email.includes("@")) errs.email = "Invalid email";
      if (password.length < 8) errs.password = "Password must be 8+ characters";
      return errs;
    };

    预期结果

    Validation logic 是 ready 到 use.

  3. 3

    构建表单使用 controlled 输入 and 错误 display

    渲染表单使用 controlled 输入. Show 错误消息 below 每个字段当 错误 exist.

    代码
    <form onSubmit={handleSubmit}>
      <input value={email} onChange={e => setEmail(e.target.value)} placeholder="Email" />
      {errors.email && <span>{errors.email}</span>}
      <input type="password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Password" />
      {errors.password && <span>{errors.password}</span>}
      <button type="submit">Register</button>
    </form>

    预期结果

    表单字段更新 as 你类型, 错误 show 当无效.

  4. 4

    Handle 表单 submission

    On 提交, prevent 默认, 运行 validation, and 仅 proceed 如果那里是 否错误.

    代码
    const handleSubmit = (e) => {
      e.preventDefault();
      const errs = validate();
      if (Object.keys(errs).length > 0) {
        setErrors(errs);
      } else {
        setErrors({});
        alert("Registration successful!");
      }
    };

    预期结果

    提交使用无效数据 shows 错误. 有效数据 shows 成功.

  5. 5

    添加状态管理与事件处理

    使用 useState 管理组件状态,为交互元素添加 onClick/onChange 事件处理。状态是 React 组件的核心,事件处理让组件响应用户操作。

    代码
    import { useState } from "react";
    
    export function MyComponent() {
      const [count, setCount] = useState(0);
      const [text, setText] = useState("");
    
      return (
        <div>
          <button onClick={() => setCount(c => c + 1)}>
            Count: {count}
          </button>
          <input
            value={text}
            onChange={(e) => setText(e.target.value)}
          />
        </div>
      );
    }

    预期结果

    点击按钮计数递增;输入框内容随键入实时更新。

自己动手试试

你学到了什么

你学习到 构建 controlled 表单使用真实-时间 validation in React: 状态持有输入值, validation 运行 on 提交, and conditional 渲染 shows 错误. 这个模式 scales 到复杂表单.

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题