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

React Hook Form自定义输入组件中minLength、maxLength校验规则失效问题求助

React Hook Form自定义输入组件中minLength、maxLength校验规则失效问题求助

大家好,我在React项目里用React Hook Form处理表单校验,直接使用原生<input>元素时一切正常,但尝试把输入框封装成自定义组件后就遇到了问题——minLength和maxLength这类校验规则没办法正常触发,始终只有required校验在生效。实在摸不着头绪,麻烦大家帮我看看哪里出问题了!

以下是我的代码示例:

父组件(Parent.jsx)

import { useForm } from "react-hook-form";
import Input from "./Components/Input.jsx";
import Button from "./Components/Button.jsx";

export default function Parent() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();

  const login = (data) => {
    console.log("Form Data:", data); 
  };

  return (
    <div className="App">
      <div className="container">
        <form onSubmit={handleSubmit(login)}>
          <Input
            type="text"
            name="username"
            {...register("username", {
              required: {
                value: true,
                message: "Username is required",
              },
              minLength: {
                value: 5,
                message: "Too Few Characters",
              },
               maxLength: {
                value: 15,
                message: "username length should not exceed 15",
              },
            })}
          />
          {errors.username && <p className="red">{errors.username.message}</p>}

          <Input
            type="password"
            name="password"
            {...register("password", {
              required: {
                value: true,
                message: "password is required",
              },
              minLength: {
                value: 6,
                message: "Password length should be greater than 6",
              },
              maxLength: {
                value: 15,
                message: "Password length should not exceed 15",
              },
            })}
          />
          {errors.password && <p className="error-red">{errors.password.message}</p>}

          <Button type="submit" />
        </form>
      </div>
    </div>
  );
}

自定义输入组件(Input.jsx)

import { forwardRef } from "react";
const Input = forwardRef(function Input(
  { type = "text", name = "", ...props },
  ref
) {
  return (
   <>
      <input
        placeholder=" "
        className="txt-input"
        type={type}
        ref={ref}
        {...props}
      />
      {name && (
        <label className="label-placeholder">
          {name.charAt(0).toUpperCase() + name.slice(1)}
        </label>
      )}
   </>
  );
});

export default Input;

我已经尝试了以下操作,但问题还是没解决:

  • 使用forwardRef将React Hook Form的ref传递给原生<input>元素
  • 将父组件的所有props(比如onChange、onBlur)都传递给了自定义组件

希望有经验的朋友能帮我找出问题所在,谢谢!

备注:内容来源于stack exchange,提问作者Sk Badsha

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:19:31