Have you ever built a form in React, only to realise you have to spend time writing endless validation logic, handling errors manually, and dealing with inconsistent user input? it's quite frustrating because a simple mistake in a field can break an entire submission. That's where Yup comes in.
Yup is a powerful schema validation library that helps you to enforce rules on React forms and fields effortlessly, combined with React hook form, it allows you to build highly efficient forms with minimal boilerplate code, giving your users instant feedback if a form field is filled out incorrectly.
This guide will explain what yup validation is, how to integrate with React hook form and some practical examples to get you started.
What is Yup?
Definition and Origin
Yup is a schema builder for JavaScript applications, it allows you to validate data against a schema and transform data in your applications easily. It was originally inspired by Joi, a popular validation library, but Yup is optimized for client-side use, making it perfect for form validation with React.
While Zod is another popular alternative, especially favored for its TypeScript support, Yup remains a widely used choice due to its flexibility and seamless integration with React applications.
Why use Yup for validation?
By using Yup, you can simplify form validation while keeping your codebase clean and scalable.
It has a declarative validations schema allowing you to define complex validation rules in a clean and readable format.
It encourages you to centralize validation logic for multiple forms making it reusable and maintainable.
It's lightweight and performant with minimal overhead making it perfect for client side use.
Features of Yup
Yup provides you with a declarative way to validate form data in JavaScript apps. It has a set of features which make it a flexible and efficient choice for handling validation in React, React hook form, and other frameworks.
Type checking
Type checking reduces validation errors by making sure that form inputs have the correct data type. For example, forcing a field to accept a certain data type like numbers.
1const schema = yup.object({
2 age: yup.number(), // Ensures the value is a number
3});
Chaining validators
Yup allows you yo chain multiple validation rules for a single field, so you can create flexible and custom validation logic.
1const schema = yup.object({
2 username: yup.string().min(3).max(15).required()
3});
Conditional validation
Yup also supports dynamic validation rules that depend on other field values, this can be useful for multi-step forms or complex business logic.
1const schema = yup.object({
2 password: yup.string().required(),
3 confirmPassword: yup.string().oneOf([yup.ref("password")], "Passwords must match"),
4});
Custom error messages
Yup allows you to provide user friendly error messages instead of generic system errors, which improves form usability.
1const schema = yup.object({
2 email: yup.string().email("Enter a valid email address").required("Email is required"),
3});
Data transformations
You can also modify input values before validation, for example you can trim whitespace, convert strings to lowercase, or format dates.
1const schema = yup.object({
2 username: yup.string().trim().lowercase(),
3});
Here are some of the most commonly used built in validation methods that yup offers at a glance:
Method | Functionality |
---|---|
.required() | Ensures a field is not empty |
.email() | Validates email format |
.min() | Sets a minimum value or length |
.max() | Sets a maximum value or length |
.matches() | Validates against custom regex patterns |
Understanding Yup Schema in React Hook Form
A Yup schema is a structured blueprint that defines the rules and constraints for form validation. It allows you to declare what your expected data types, required fields, and validation conditions are in a clean and reusable way.
When using Yup, instead of manually writing out all of your validation logic, you define a schema that will enforce those rules automatically.
Basic Yup schema syntax
Yup schemas are normally created using yup.object()
, and consists of fields with their respective validation rules.
For instance here's a basic schema validating a user registration form:
1import * as yup from "yup";
2
3const userSchema = yup.object({
4 name: yup.string().required("Name is required"),
5 email: yup.string().email("Invalid email").required("Email is required"),
6 age: yup.number().min(18, "Must be at least 18").required("Age is required"),
7});
In the above code, each field in the schema represents a form input, validation rules like .required()
are chained with other methods to define constraints, this schema can be used to validate form data before submission.
Common use cases of Yup schemas
Yup supports nested objects, allowing you to validate structured data (an address inside a user profile object):
1const userSchema = yup.object({
2 name: yup.string().required(),
3 address: yup.object({
4 street: yup.string().required(),
5 city: yup.string().required(),
6 zip: yup.string().matches(/^\d{5}$/, "Invalid ZIP code"),
7 }),
8});
This helps to validate complex form structures, it also ensures all nested fields meet validation criteria.
Yup also allows validation of arrays of objects, this makes it very useful for forms which may have repeating fields (like a list of phone numbers):
1const userSchema = yup.object({
2 contacts: yup.array().of(
3 yup.object({
4 type: yup.string().oneOf(["home", "work", "mobile"]),
5 number: yup.string().matches(/^\d+$/, "Must be a valid number"),
6 })
7 ),
8});
This is great for multi-step forms or dynamically added fields, and it ensures each item in an array follows the expected structure.
Lastly instead of duplicating validation logic across multiple forms, you can define reusable Yup schemas:
1const emailSchema = yup.string().email("Invalid email").required();
2const passwordSchema = yup.string().min(8, "Must be at least 8 characters");
3
4const loginSchema = yup.object({
5 email: emailSchema,
6 password: passwordSchema,
7});
8
9const registerSchema = yup.object({
10 email: emailSchema,
11 password: passwordSchema,
12 confirmPassword: yup
13 .string()
14 .oneOf([yup.ref("password")], "Passwords must match"),
15});
This promotes code reuse and maintainability as well as making sure you have consistent validation rules across different forms in your application.
Yup validation with schema
Once you have defined all of your Yup schemas, you can use them to validate data. Yup provides you with both synchronous and asynchronous validation methods, as well as support for custom validation logic.
Synchronous validation
Synchronous validation runs instantly without returning a promise, making it useful for when validation does not involve asynchronous operations (simple field checks)
The method .validateSync()
validates data synchronously, throwing an error if validation fails.
1import * as yup from "yup";
2
3const schema = yup.object({
4 name: yup.string().required(),
5 age: yup.number().min(18).required(),
6});
7
8try {
9 schema.validateSync({ name: "John", age: 17 }); // Throws validation error
10} catch (error) {
11 console.log(error.message); // "age must be at least 18"
12}
Asynchronous validation
In real world applications, validation will at some point require asynchronous checks-such as verifying a username's availability in a database or checking external APIs for information.
The .validate()
method returns a promise, making it suitable for async operations.
1const schema = yup.object({
2 username: yup.string().required(),
3});
4
5const validateData = async () => {
6 try {
7 const data = await schema.validate({ username: "" });
8 console.log("Valid!", data);
9 } catch (error) {
10 console.log("Validation failed:", error.message);
11 }
12};
Custom validation logic
Yup allows you to make custom validation rules using the .test()
method. This is useful when built-in validation methods don't meet your specific needs.
For example the following validation makes sure that a password contains at least one number:
1const passwordSchema = yup.string()
2 .min(8, "Password must be at least 8 characters")
3 .test("contains-number", "Password must include a number", (value) => {
4 return /\d/.test(value); // Ensures at least one number exists
5 });
6
7passwordSchema
8 .validate("password") // No number, so this fails
9 .catch((error) => console.log(error.message)); // "Password must include a number"
You can also use .test()
for more complex validations, for instance maybe you want to validate a field based on another fields value (password confirmation):
1const schema = yup.object({
2 password: yup.string().required(),
3 confirmPassword: yup.string().test(
4 "match-password",
5 "Passwords must match",
6 function (value) {
7 return value === this.parent.password;
8 }
9 ),
10});
11
12schema
13 .validate({ password: "123456", confirmPassword: "123" })
14 .catch((error) => console.log(error.message)); // "Passwords must match"
The above Yup schema checks if the confirmPassword
field matches the password
field all in one .test()
method.
How to validate forms with Yup
Before introducing React Hook Form, the following example will show how Yup works independently in a basic form validation scenario.
First define a Yup schema, you can create a simple schema that ensures that the object has:
- A name field which is required
- An email field which must be a valid email
- An age field that must be at least 18 years old
1import * as yup from "yup";
2
3const schema = yup.object({
4 name: yup.string().required("Name is required"),
5 email: yup.string().email("Invalid email format").required("Email is required"),
6 age: yup.number().min(18, "You must be at least 18").required("Age is required"),
7});
Now you can use the .validate()
method to validate a sample form submission.
1const formData = { name: "", email: "invalid-email", age: 15 };
2
3schema.validate(formData, { abortEarly: false })
4 .then(() => console.log("Validation passed!"))
5 .catch((error) => console.log(error.errors));
When validation fails, Yup will return an array of error messages:
1["Name is required", "Invalid email format", "You must be at least 18"]
Right now, you have to manually check for errors and display them in the UI, which is repetitive and inefficient, this is where React Hook Form excels. Let's see how React Hook Form can simplify the validation process.
Yup validation with React hook form
Instead of manually checking for validation errors and then having to display them, you can use React Hook Form to make your form handling more efficient (minimal re-renders), easier to manage (auto triggers validation) and easier to integrate with Yup in general.
Step 1: Create project and Install dependencies
First create a folder to host your new project in:
1mkdir yup-example
Create the frontend for the project:
1npm create vite@latest yup-frontend --template react
Change into the yup-frontend
directory and run the following command to install react-hook-form
and Yup's resolver package:
1npm install react-hook-form @hookform/resolvers yup
Step 2: Create the form component
Now, create a form component called SignupForm
in the root directory with the following code:
1import React from "react";
2import { useForm } from "react-hook-form";
3import { yupResolver } from "@hookform/resolvers/yup";
4import * as yup from "yup";
5
6// Define Yup Schema
7const schema = yup.object({
8 name: yup.string().required("Name is required"),
9 email: yup.string().email("Invalid email").required("Email is required"),
10 age: yup.number().min(18, "You must be at least 18").required("Age is required"),
11});
12
13const SignupForm = () => {
14 const { register, handleSubmit, formState: { errors } } = useForm({
15 resolver: yupResolver(schema),
16 });
17
18 const onSubmit = (data) => {
19 console.log("Form Submitted:", data);
20 };
21
22 return (
23 <form onSubmit={handleSubmit(onSubmit)}>
24 <div>
25 <label>Name:</label>
26 <input {...register("name")} />
27 <p>{errors.name?.message}</p>
28 </div>
29
30 <div>
31 <label>Email:</label>
32 <input {...register("email")} />
33 <p>{errors.email?.message}</p>
34 </div>
35
36 <div>
37 <label>Age:</label>
38 <input type="number" {...register("age")} />
39 <p>{errors.age?.message}</p>
40 </div>
41
42 <button type="submit">Register</button>
43 </form>
44 );
45};
46
47export default SignupForm;
In the above code the register()
function binds the inputs to React Hook Form, the resolver: yupResolver(schema)
automatically validates data with Yup, and errors.name?.message
displays validation errors.
Now replace the code in App.jsx
with the following:
1import reactLogo from "./assets/react.svg";
2import viteLogo from "/vite.svg";
3import "./App.css";
4import SignupForm from "./SignupForm";
5
6function App() {
7 return (
8 <>
9 <div>
10 <a href="https://vite.dev" target="_blank" rel="noopener noreferrer">
11 <img src={viteLogo} className="logo" alt="Vite logo" />
12 </a>
13 <a href="https://react.dev" target="_blank" rel="noopener noreferrer">
14 <img src={reactLogo} className="logo react" alt="React logo" />
15 </a>
16 </div>
17 <h1>Form Example</h1>
18 <SignupForm />
19 </>
20 );
21}
22
23export default App;
The above code is just importing and then displaying the SignupForm
in the App
component.
Start the app with npm run dev
and navigate to http://localhost:5173/
in your browser, the form should appear, try entering some numbers for the name and pressing the button to register.
As you can see entering a number for the name field and leaving email blank shows validation errors.
Set up a Strapi Backend
Now that you have form validation in place, let's extend the form to submit user data to a Strapi backend.
Strapi is a headless CMS that lets you easily store and manage form data, with Strapi you can:
- Spin up a backend effortlessly.
- Save form submissions in a database.
- Send form data via API without having to set up a full backend.
- Get an admin panel to view all submitted data.
Step 1: Set up Strapi locally
In your terminal, open another tab and navigate back to yup-example
and then run the following command:
1npx create-strapi@latest strapi-backend --quickstart
This should auto start and bring you to the admin panel, create a new admin user and proceed.
Step 2: Create a "YupUser" collection in Strapi
Now under content-type-builder create a new collection (which are entities where we can store data) called - YupUser
by clicking on Create new collection type
and add the name
, email
, and age
fields respectively:
Now save it by clicking on save
in the top right hand corner.
You will also need to enable public API access so the form can send data, you find this under the settings -> Roles -> Public -> Permissions:
Click to select all and then save in the top right hand corner.
Step 3: Modify the form to submit data to Strapi
Now we want to modify the frontend code so that when the form is submitted it sends a POST
request to the Strapi backend, if the request is successful we want to log a success message, if something goes wrong, we catch the error and display it.
So change the onSubmit
function in the SignupForm
component to the following:
1const onSubmit = async (data) => {
2 try {
3 const response = await fetch("http://localhost:1337/api/users", {
4 method: "POST",
5 headers: { "Content-Type": "application/json" },
6 body: JSON.stringify({ data }),
7 });
8
9 if (!response.ok) throw new Error("Failed to submit form");
10
11 console.log("Form submitted successfully!");
12 } catch (error) {
13 console.error("Error:", error);
14 }
15};
Now try navigating to the app and entering a user.
Provided you enter valid data to the form and submit you will see a new user appear in the Strapi dashboard, saved to the database, If you enter incorrect information our validation will stop it before it has a chance to be sent to the database.
Why use Strapi as a Backend for your React apps?
Strapi is a powerful headless CMS that simplifies backend development, it allows you to quickly set up APIs and manage content without having to write complex backend logic.
What's new in Strapi v5?
We have recently released a new version of our platform and here are just a few of its benefits:
Improved API performance: Faster response times for real-time apps.
Better role management: More granular access controls.
Plugin system enhancements: Extend Strapi with custom plugins and community add-ons.
By using Strapi with a frontend library like React, you get a flexible, efficient, and maintainable backend without the usual time constraint and complexity, allowing you to focus on building great frontends and complex business logic.
Github Source Code
You can find the full code example repository here.
Conclusion
Integrating Yup with React Hook Form provides a powerful, efficient, and scalable approach to React forms validation in React applications. By leveraging schema-based validation, you can ensure consistent, reusable, and maintainable form logic while reducing boilerplate code.
Key Takeaways
- Yup simplifies validation logic with declarative schemas, reducing manual error handling.
- React Hook Form enhances performance with minimal re-renders and automatic validation.
- Combining both tools streamlines form development, ensuring a better user experience and cleaner codebase.
- Extending this setup with Strapi as a backend enables seamless data storage, API integration, and better form data management.
By following this guide, you now have a fully functional validation system that can handle everything from basic field checks to complex, conditional validations. Whether you're working on authentication forms, registration pages, or multi-step wizards, this combination ensures your forms are fast, reliable, and user-friendly.
Hey! 👋 I'm Mike, a seasoned web developer with 5 years of full-stack expertise. Passionate about tech's impact on the world, I'm on a journey to blend code with compelling stories. Let's explore the tech landscape together! 🚀✍️