You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Hook-Form分组输入Register验证提示不生效问题求助

React-Hook-Form嵌套字段验证错误提示修复方案

你遇到的问题核心是:嵌套字段的错误信息会按照字段的层级结构存储在errors对象中,不能像单字段那样直接通过errors.fieldName访问。以下是具体的修复方案和示例代码:

完整可运行示例代码

import { useForm } from "react-hook-form";

function NestedForm() {
  const { register, formState: { errors }, handleSubmit } = useForm({
    // 必须初始化对应嵌套结构的默认值,确保表单状态层级正确
    defaultValues: {
      name: {
        first_name: "",
        last_name: ""
      }
    }
  });

  const onSubmit = (data) => {
    console.log("提交数据:", data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div style={{ marginBottom: "1rem" }}>
        <label>名字</label>
        <input
          {...register("name.first_name", {
            required: "名字不能为空",
            minLength: {
              value: 2,
              message: "名字长度不能少于2个字符"
            }
          })}
          style={{ marginLeft: "0.5rem" }}
        />
        {/* 按层级访问错误信息,用可选链避免未定义报错 */}
        {errors.name?.first_name && (
          <p style={{ color: "red", margin: "0.2rem 0 0 0" }}>
            {errors.name.first_name.message}
          </p>
        )}
      </div>

      <div style={{ marginBottom: "1rem" }}>
        <label>姓氏</label>
        <input
          {...register("name.last_name", {
            required: "姓氏不能为空"
          })}
          style={{ marginLeft: "0.5rem" }}
        />
        {errors.name?.last_name && (
          <p style={{ color: "red", margin: "0.2rem 0 0 0" }}>
            {errors.name.last_name.message}
          </p>
        )}
      </div>

      <button type="submit">提交表单</button>
    </form>
  );
}

export default NestedForm;

关键注意事项

  • 初始化默认值:必须在useForm的配置中传入和嵌套字段结构一致的defaultValues,这是React-Hook-Form正确维护嵌套字段状态的前提。
  • 字段注册语法:注册嵌套字段时使用点语法(如name.first_name),和defaultValues的结构完全对应。
  • 错误信息访问:错误对象会跟随字段层级嵌套,比如name.first_name的错误信息存储在errors.name.first_name中,使用可选链?.可以避免当errors.name不存在时抛出异常。

备选方案:使用getFieldState

如果表单结构复杂,也可以用getFieldState方法直接获取指定字段的状态,包括错误信息:

import { useForm, getFieldState } from "react-hook-form";

// 在组件内部
const firstNameState = getFieldState("name.first_name", formState);

// 显示错误
{firstNameState.error && <p style={{ color: "red" }}>{firstNameState.error.message}</p>}

内容的提问来源于stack exchange,提问作者swiftah_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 08:37:54