Easy Form Validation with React Hook Form & Yup
React Hook Form and Yup are powerful libraries that can make form handling and validation much easier in your React applications.
React Hook Form
React Hook Form is a library that simplifies form state management in React applications. It uses hooks, making it easy to integrate into your functional components.
Yup
Yup is a JavaScript schema builder for value parsing and validation. It allows you to define a schema for your form data and use it to validate the form inputs.
Combining React Hook Form and Yup
React Hook Form can be combined with Yup for efficient and easy form validation.
Here’s a simple example:
First, we need to define our validation schema with Yup:
import * as yup from 'yup';
const validationSchema = yup.object().shape({
firstName: yup.string().required("First name is required"),
lastName: yup.string().required("Last name is required"),
});
This schema specifies that both firstName and lastName are required fields.
Next, we create our form component:
import React from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
function MyForm() {
const { register, handleSubmit, formState: { errors }, reset } = useForm({
resolver: yupResolver(validationSchema),
});
const onSubmit = data => {
console.log(data);
reset();
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<input {...register("firstName")} />
{errors.firstName && <p>{errors.firstName.message}</p>}
<input {...register("lastName")} />
{errors.lastName && <p>{errors.lastName.message}</p>}
<input type="submit" />
</form>
);
}
export default MyForm;
In this component, we use the useForm hook from React Hook Form. We pass an options object to useForm, specifying yupResolver(validationSchema) as the resolver. This tells React Hook Form to use our Yup validation schema for validating the form.
The useForm hook returns several methods and values that we can use in our component, including:
- register (for registering inputs)
- handleSubmit (for handling form submission)
- errors (an object containing any validation errors)
- reset (a function to reset the form).
We then create form inputs for firstName and lastName using the register function from useForm.
If there are any validation errors for these fields, we display them under the corresponding input.
Finally, we create a submit button for our form. When the form is submitted, the onSubmit function is called. This function logs the form data to the console and resets the form.