Mastering Form Validation with Yup and Hook Form: Password and Confirm Password
Tags: javascript, webdev, hookform, validation
Published: 2023-04-16 10:59:22

Hello Everyone 👋, Don't worry 😓 about validation. Today iam going put my 100% effort so you can easily understand what actually is:
- Form validation📝
- Why it is important 🔐
- How we perform form validation in react using yup and hook form.

Hurray, Let's start




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6w3wqtw4bi4e6qhqznk.gif)







# 1. Introduction
 📝✅👀 Form validation is the process of checking whether the data entered by the user in the web form is correct ✔️ or not❌.

It ensures that the data entered by the user is correct or not such as valid email address, valid phone format, password and  confirm password match ...etc

In react ecosystem, we have several options to validate the form. Thanks god, we have a huge options 💖🤗 but many libraries have huge boilerplate which leads them to difficult for use and performance issues. 

Keeping all these points in mind, I always looked for a soltution that is very simple 🤗 and easy to use. Not only that searching 🔎 for  great performace. 

That's why i always go for `react hook form` and for schema validation always with `yup`.

## let's see how easily you understand form validation.
### Easy peasy 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9mdamg0hepqxjl5ttt0w.gif)

# 2. setting up a Form with `hook form` and `yup`

First, we need to add the following dependencies in our react app:
```bash
npm install react-hook-form @hookform/resolvers yup
```

let's create a form at `App.jsx` :

```react
import React from "react";

const App = () => {
  return (
    <form>
      <h2>Lets sign you in. </h2>
      <br />

      <input placeholder="email" type="email" required />
      <br />

      <input
        placeholder="password"
        type="password"
        required
      />
      <br />
 <input
        placeholder="Confirm Password"
        type="password"
        required
      />
      <br />

      <button type="submit">Submit Form</button>
    </form>
  );
};

export default App;
```


let's import `hook form` here at `app.jsx` :

```react
import React from "react";
import { useForm } from "react-hook-form";
//all code below remains same and hidden for simplicity
```

Let's get these things from `useForm` :

```react
import React from "react";
import { useForm } from "react-hook-form";


const App = () => {
const { register, handleSubmit, formState: { errors }, reset } = useForm();
return (
//remains same and hidden for simplicity
)}

export default App;
```

### useForm
- register: This method allow to registration form elements and used for applying validation.
- handleSubmit : This method takes all the form data after Submission.
- reset : This methods resets the form.
- formState: {errors} : We are using `formState`to return errors in easier way.

Now, it's time to import yup in our project and make create form schema using this:

```react
//app.jsx
//hidden for simplicity
import * as yup from "yup";

const formSchema = yup.object().shape({
email:yup.string().email().required("Email is required"),
  password: yup.string()
            .required('Password is required')
            .min(6, 'Password must be at least 6 characters'),
        confirmPassword: yup.string()
            .required('Confirm Password is required')
            .oneOf([yup.ref('password')], 'Passwords must match')
//custom error message inside function like "passwords must match"
// "Confirm password is required"
//password must be at least 6 characters
//Email is required
});

//hidden for simplicity
const App = () =>{
//hidden for simplicity
}

export default App;
```

Don't be confused here. We create a schema for three form fields email, password and confirmPassword. The message inside the function indicates a custom error message. 

we have to import `@hookform/resolvers` so that we can use `formSchema` with `hook form`.


```react
import { yupResolver } from "@hookform/resolvers/yup";
//hidden for simplicity

const App = ()=>{
 const { register, handleSubmit, formState: { errors }, reset } = useForm({
    resolver: yupResolver(formSchema),
  });

return(
//hidden for simplicity
)}

export default App;
```

Now we have to create a function that executes after form submission.

```react
//hidden for simplicity

const App = ()=>{

const onSubmitHandler = (formData)=>{
console.log(formData);
}

return(
<form onSubmit={handleSubmit(onSumbitHandler)}>
      // Hidden for simplicity
    </form>
)
}

export default App;
```

The next and most important move is to register our input fields according to our `formSchema` : 

```react
//hidden imported modules for simplicity


const App = () => {
  // Hidden for simplicity
  return (
    <form onSubmit={handleSubmit(onSubmitHandler)}>
      <h2>Lets sign you in.</h2>
      <br />

      <input {...register("email")} placeholder="email" type="email" required />
      <br />

      <input
        {...register("password")}
        placeholder="password"
        type="password"
        required
      />
      <br />

<input
        {...register("confirmPassword")}
        placeholder="Confirm Password"
        type="password"
        required
      />
      <br />

      <button type="submit">Submit Form</button>
    </form>
  );
};
```

Last show the error message if any validation failed according to our `formSchema` defined:

```react
const App = () => {
  // Hidden for simplicity
  return (
    <form onSubmit={handleSubmit(onSubmitHandler)}>
      <h2>Lets sign you in.</h2>
      <br />

      <input {...register("email")} placeholder="email" type="email" required />
      <p>{errors.email?.message}</p>
      <br />

      <input
        {...register("password")}
        placeholder="password"
        type="password"
        required
      />
      <p>{errors.password?.message}</p>
      <br />
 <input
        {...register("confirmPassword")}
        placeholder="Confirm Password"
        type="password"
        required
      />
      <p>{errors.confirmPassword?.message}</p>
      <br />

      <button type="submit">Submit Form</button>
    </form>
  );
};

export default App;
```

Thank God 🙏, It's finished now.
 The code 👨‍💻 should look like this:

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

const formSchema = yup.object().shape({
  email: yup.string().email().required("Email is required"),
  password: yup.string()
    .required('Password is required')
    .min(6, 'Password must be at least 6 characters'),
  confirmPassword: yup.string()
    .required('Confirm Password is required')
    .oneOf([yup.ref('password')], 'Passwords must match')
})

const App = () => {
  const { register, handleSubmit, formState: { errors }, reset } = useForm({
    resolver: yupResolver(formSchema),
  });
  const onSubmitHandler = (data) => {
    console.log({ data });
    reset();
  };
  return (
    <form onSubmit={handleSubmit(onSubmitHandler)}>
      <h2>Lets sign you in.</h2>
      <br />

      <input {...register("email")} placeholder="email" type="email" required />
      <p>{errors.email?.message}</p>
      <br />

      <input
        {...register("password")}
        placeholder="password"
        type="password"
        required
      />
      <p>{errors.password?.message}</p>
      <br />

      <input
        {...register("confimPassword")}
        placeholder="Confirm Password"
        type="password"
        required
      />

      <p>{errors.confirmPassword?.message}</p>

      <br />

      <button type="submit">Submit Form</button>
    </form>
  );
};

export default App;
```
Final touch looks like this 🤗🤗.




![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pzw69l52pi29wm8rd22z.gif)




Thank you everyone. Please feel free to leave 🤗 a comment. It motivates me too.