DEV Community

Cover image for Mastering Form Validation with Yup and Hook Form: Password and Confirm Password
krishna-Tiwari
krishna-Tiwari

Posted on • Updated on

Mastering Form Validation with Yup and Hook Form: Password and Confirm Password

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

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

2. setting up a Form with hook form and yup

First, we need to add the following dependencies in our react app:

npm install react-hook-form @hookform/resolvers yup
Enter fullscreen mode Exit fullscreen mode

let's create a form at App.jsx :

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

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

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

Let's get these things from useForm :

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

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 formStateto return errors in easier way.

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

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

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.

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

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

//hidden for simplicity

const App = ()=>{

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

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

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

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

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

Thank God πŸ™, It's finished now.
The code πŸ‘¨β€πŸ’» should look like this:

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

Final touch looks like this πŸ€—πŸ€—.

Image description

Thank you everyone. Please feel free to leave πŸ€— a comment. It motivates me too.

Top comments (3)

Collapse
 
nabinghimire profile image
Nabin-Ghimire

I'm searching for this for a long time. Finally, I got it. Thanks to you.

Collapse
 
krishnacyber profile image
krishna-Tiwari

Iam feel glad to hear that. It helped you a lot. πŸ’–πŸ’–

Collapse
 
nabinghimire profile image
Nabin-Ghimire

Your greatness.