Mastering Form Validation with Yup and Hook Form: Password and Confirm Password
krishna-Tiwari
Posted on April 16, 2023
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
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
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
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;
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
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;
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:
//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
.
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.
//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
:
//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:
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:
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 π€π€.
Thank you everyone. Please feel free to leave π€ a comment. It motivates me too.
Posted on April 16, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
April 16, 2023