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

React-hook-form无法识别输入值,密码字段持续提示必填错误

React Hook Form登录表单无法识别输入值,密码字段始终提示必填错误

问题核心是你同时混用了React Hook Form的register和自定义useState受控逻辑——手动给输入框绑定value和onChange会完全绕过RHF的表单状态管理,导致RHF无法追踪用户输入内容,因此持续触发必填校验错误。

解决步骤:

  1. 删除自定义的username、password状态变量,让RHF全权接管表单值
  2. 移除输入框上的value和onChange属性,register方法会自动绑定必要的事件与值

修改后的完整代码:

function SignIn({ setIsLoginView }: LoginProps) {
  const {
    register,
    handleSubmit,
    watch,
    formState: { errors, isDirty, isValid, dirtyFields, touchedFields },
  } = useForm<IFormInput>({
    defaultValues: {
      userId: "",
      userPW: "",
    },
  });

  // 用RHF的watch方法监听密码值,用于大小写锁定检测
  const userPW = watch("userPW");

  const onSubmit: SubmitHandler<IFormInput> = (data) => {
    RequestSignin({ username: data.userId, password: data.userPW })
      .then((res) => {
        console.log(res, data.userId);
        setIsLoginView(!setIsLoginView);
        setStoredToken(res.access_token);
        setAuthenticated();
        dispatch(setLogin(data.userId));
      })
      .catch((error) => console.error);
  };

  // 保留大小写锁定检测逻辑
  const checkCapsLock = (e: KeyboardEvent) => {
    isCapsLockOn = e.getModifierState("CapsLock");
  };

  return (
    <div>
      <form
        onSubmit={handleSubmit(onSubmit)}
        className="w-1/4"
      >
        <div className="mb-3">
          <label className="block text-sm font-medium mb-1">Username</label>
          <input
            {...register("userId", {
              required: "This field is required",
              maxLength: { value: 20, message: "Maximum length is 20 letters." },
              minLength: { value: 4, message: "Minimum length is 4 letters." },
              // pattern: { value: /^[a-z]+$/, message: "Lower alphabetic letter only." },
            })}
            type="text"
            className="w-full px-3 py-2 rounded text-gray-700 dark:text-gray-200 dark:bg-stone-900"
          />
          <span className="text-rose-600 text-xs h-3">{errors?.userId?.message}</span>
        </div>
        <div className="mb-4">
          <label className="block text-sm font-medium mb-1">Password</label>
          <input
            {...register("userPW", {
              required: "This field is required",
              minLength: {
                value: 4,
                message: "Please input more than 4 characters.",
              },
            })}
            type="password"
            className="w-full px-3 py-2 rounded text-gray-700 dark:text-gray-200 dark:bg-stone-900"
            onKeyUp={checkCapsLock}
          />
          {errors.userPW && <span className="text-rose-600 text-xs">{(errors.userPW as FieldError).message}</span>}
          {isCapsLockOn && <span className="text-rose-600 text-xs">Caps Lock is ON</span>}
        </div>
        <input
          type="submit"
          value="Sign In"
          className="bg-teal-600 mt-8 text-white font-bold px-4 py-2 rounded hover:bg-teal-700 m-auto flex w-1/2 justify-center"
        />
      </form>

      <div className="flex justify-center gap-3 mt-10">
        <span className="text-base/10">{optInText[1]}</span>
        <input
          type="submit"
          value={optInText[2]}
          className=" text-teal-500 font-bold hover:text-teal-400 flex"
          onClick={() => setViewSignUp(!viewSignUp)}
        />
      </div>
    </div>
  );
}

补充提示:

如果后续需要手动访问或修改表单值,优先使用RHF提供的watch(监听值)、setValue(设置值)方法,避免自定义状态导致表单状态与校验逻辑不同步。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 08:02:05