React-hook-form not storing errors

I am on video 7 “Applying Validation” in the “Building Forms” section.

The built-in form validation in the input element seems to be preventing the formState property from storing the errors.

I get an error message that is displayed to me in the browser (not the console) when I fail to meet the criteria for the form. The formState.errors property is not updated at all. In Mosh’s case, no errors are shown outside of the ones in the console.

I tried disabling bootstrap, but it did nothing. I also tried to incorporate the preventDefault() function mentioned previously, but adding this to the onSubmit() function prevented me from passing it as a reference into handleSubmit().

Here is the source (the component is implemented as a self-closing element in App.tsx):

import { FieldValues } from "react-hook-form/dist/types";
import { useForm } from "react-hook-form";

const ReactHookForm = () => {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
  console.log(errors);

  const onSubmit = (data: FieldValues) => {
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div className="mb-3">
        <label htmlFor="name" className="form-label">
          Name
        </label>
        <input
          {...(register("name"),
          { required: true, minLength: 3, maxLength: 20 })}
          id="name"
          type="text"
          className="form-control"
        />
      </div>
      <div className="mb-3">
        <label htmlFor="age" className="form-label">
          Age
        </label>
        <input
          {...register("age")}
          id="age"
          type="number"
          className="form-control"
        />
      </div>
      <button className="btn btn-primary" type="submit">
        Submit
      </button>
    </form>
  );
};

export default ReactHookForm;

1 Like

Nevermind, I fixed it. It was an error in parentheses. I wasn’t passing the object with the form validation requirements into the register() function.

// wrong
{...(register("name"), { required: true, minLength: 3, maxLength: 20 })}

// right
{...register("name", { required: true, minLength: 3, maxLength: 20 })}
1 Like

Thank you! You wonderful person! I was smashing my head against the wall cursing the gods about why the hell this was not working. Can’t believe it was a stupid typo but hey. Thanks again!

1 Like

Thanks for posting the solution, just was stumbling into the exact same error!