DEV Community

Tasfia Islam
Tasfia Islam

Posted on

Form validation with react hook form and yup

Installation

Let's install the code dependencies

npm install react-hook-form @hookform/resolvers yup

Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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),
  });
Enter fullscreen mode Exit fullscreen mode

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>
Enter fullscreen mode Exit fullscreen mode

Our submit handler which also resets our form after submission:

const onSubmitHandler = (values: FieldValues) => {
    console.log({ values});
    // after submit code
    reset();
  };
Enter fullscreen mode Exit fullscreen mode

Our form looks like this

Product Form

When we submit without filling out required fields we show these
validation messages:

Form errors

Top comments (0)