Installation
Let's install the code dependencies
npm install react-hook-form @hookform/resolvers yup
Implementation
Create the schema for validation
import * as yup from "yup";
const Schema = yup
.object({
name: yup.string().required("Name is required."),
model: yup.string().required("Model name is required."),
})
.required();
Get the following from the useForm() hook
import { FieldValues, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
const {
register,
handleSubmit,
formState: { errors },
} = useForm({
resolver: yupResolver(Schema),
});
Let's create a simple form
<form
className="bg-white"
onSubmit={handleSubmit(onSubmitHandler)}
encType="multipart/form-data"
id={formId}
>
<div className={formInputClass}>
<Label label="Product Name" htmlFor="name" isRequired />
<input
className={customFieldStyle}
id="name"
{...register("name")}
type="text"
placeholder="Enter the product name"
/>
<FormErrorText errorMsg={errors?.name?.message} />
</div>
<div className={formInputClass}>
<Label label="Model" htmlFor="model" isRequired />
<input
className={customFieldStyle}
id="model"
{...register("model")}
type="text"
placeholder="Enter the model name"
/>
<FormErrorText errorMsg={errors?.model?.message} />
</div>
</form>
Our submit handler which also resets our form after submission:
const onSubmitHandler = (values: FieldValues) => {
console.log({ values});
// after submit code
reset();
};
Our form looks like this
When we submit without filling out required fields we show these
validation messages:
Top comments (0)