Skip to main content

Advance form handling with YUP & React-hook-form

 yup and react-hook-form is your life saver.

 Yup are powerful tools in the React ecosystem for form validation and form handling. Let's explore it together.

Installation :

Go to your project and run this command.

npm install react-hook-form @hookform/resolvers yup
Work with yup and react-hook-form

 

Suppose this this your form

function EmailForm() {
  return (
    <>
      <form>
        <label htmlFor="">Firstname: </label>
        <input type="text" />
        <label htmlFor="">Email: </label>
        <input type="text" />
        <button type="submit">submit</button>
      </form>
    </>
  );
}

export default EmailForm;

Now we need to import our yup and react-hook-form to use in our project.

import { useForm } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";

Next we will construct our schema for the form data with Yup. In this example we have 2 input which is firstname and email.

firstname => "required" string with minimum length of 3 character

email => "required" email

 const informationSchema = yup.object().shape({
    firstname: yup.string().required().min(3),
    email: yup.string().email().required(),
  });

After we have schema, we also need to construct our form manager from react-hook-form

const { register,handleSubmit, formState: { errors }} = useForm({ resolver: yupResolver(informationSchema)});

as you can see on the code above "useForm" is a utility from react-hook-form which will validate by resolver with yup resolver with our information schema.

In the last step, we will make our element to use our form manager

<form onSubmit={handleSubmit(onSubmit)}>
        <label htmlFor="">Firstname: </label>
        <input type="text" {...register("firstname")} />
        <label htmlFor="">Email: </label>
        <input type="text" {...register("email")} />
        <button type="submit">submit</button>
 </form>
 {errors.firstname && <p>{errors.firstname.message}</p>}
 {errors.email && <p>{errors.email.message}</p>}

and the onSubmit function which will show errors when there is invalid firstname or email

const onSubmit = () => {
    if (errors.firstname || errors.email) {
      alert(JSON.stringify(errors));
    } else {
      alert("Form submitted successfully");
    }
  };

 

Now let's test it.

Read more on YUP

Read more on react-hook-form