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;