Yup is a JavaScript and TypeScript schema validation library that allows developers to define and enforce rules for data structures in a simple and declarative way.
It is widely used for form validation, API input validation, and structured data checks, especially in modern frontend frameworks like React. With Yup, you can validate strings, numbers, booleans, objects, arrays, and enums, as well as provide custom error messages and default values effortlessly.
It integrates seamlessly with libraries such as Formik for form handling, making it a go-to solution for both small projects and large-scale applications.
Yup Validation Syntax:
import * as yup from 'yup';
const userSchema = yup.object({
name: yup.string().required(),
age: yup.number().min(0),
email: yup.string().email().required(),
});
userSchema.validate({email: 'sharukhan@tecktol.com', name: 'Sharukhan'}).then(res => console.log(res)).catch(err => {
console.warn(err)
})
This Yup schema validates a simple user object. Each field has rules: name
must be a string and is required, age
must be a number greater than or equal to 0, and email
must be a valid email address. If you’re familiar with JavaScript objects, Yup lets you enforce rules declaratively for any object structure.
For official references and documentation:
- Yup Documentation – Comprehensive guides and examples.
- Yup GitHub Repository – Source code, releases, and community contributions.
- Yup npm Package – Installation instructions and usage stats.
Yup String Validation
Yup strings let you validate text-based fields with precision. You can enforce length constraints, pattern matching, required status, trimming, and default values directly on string fields.
This makes it easy to handle common inputs such as usernames, email addresses, and passwords, ensuring they meet your application’s rules without extra boilerplate.
import * as yup from 'yup';
const userSchema = yup.object({
username: yup.string().required("Username is required"),
email: yup.string().email("Enter a valid email").required(),
password: yup.string().min(6, "Password must be at least 6 characters"),
});
Explanation:
username
must be a string and cannot be empty.email
must match a valid email format.password
must have a minimum of 6 characters.
Our detailed Yup string validation guide dives deep into all these scenarios, including regex patterns, transformations, enums, and custom tests, so you can apply them confidently in your projects.
Yup Array Validation
Yup arrays allow you to validate lists of items in JavaScript or TypeScript. You can enforce rules such as type consistency, minimum and maximum length, required elements, and default values. Arrays are commonly used to validate inputs like lists of emails, tags, or objects in forms.
Using Yup array validation, developers can ensure that every item in the list meets the expected criteria, improving data integrity in applications.
import * as yup from 'yup';
const formSchema = yup.object({
tags: yup.array()
.of(yup.string().min(2, "Each tag must be at least 2 characters"))
.min(1, "At least one tag is required")
.max(5, "You can add up to 5 tags")
.required("Tags field is required"),
});
Explanation:
tags
is defined as a Yup array containing strings..of(yup.string().min(2))
ensures each element is a string with at least 2 characters..min(1)
and.max(5)
enforce that the array contains between 1 and 5 items..required()
makes sure the array itself is provided, preventing empty submissions.
In our Comprehensive Guide to Yup Array Validation, we delve into defining and validating arrays using Yup, covering various scenarios and best practices.
Yup Object Validation
Yup objects allow you to validate structured data with multiple fields in JavaScript or TypeScript. They are essential for handling nested data, form submissions, or complex JSON objects.
Using Yup object validation, you can define rules for each property, enforce required fields, and nest schemas for deeper structures, ensuring that all parts of an object conform to your expected data model.
import * as yup from 'yup';
const userSchema = yup.object({
name: yup.string().required("Name is required"),
email: yup.string().email("Enter a valid email").required(),
address: yup.object({
street: yup.string().required("Street is required"),
city: yup.string().required("City is required"),
zip: yup.string().matches(/^\d{5}$/, "ZIP must be 5 digits"),
}).required("Address is required"),
});
Explanation:
userSchema
is a Yup object representing a structured user data model.- Nested
address
is another Yup object, demonstrating nested schema validation. - Each field has its own validation rules, ensuring data consistency throughout the object.
To dive deeper into creating, validating, and handling nested or dynamic objects, check out our Yup object validation guide for step-by-step examples and working schemas.
Yup Number Validation
Yup numbers allow you to validate numeric fields in JavaScript or TypeScript objects. They are commonly used for inputs such as ages, prices, quantities, or scores.
With Yup number validation, you can enforce rules like minimum and maximum values, integers, positivity, and required fields, ensuring that numeric data is consistent and accurate across your application.
import * as yup from 'yup';
const productSchema = yup.object({
price: yup.number().positive("Price must be a positive number").required("Price is required"),
quantity: yup.number().integer("Quantity must be an integer").min(1, "At least 1 item is required"),
});
Explanation:
price
must be a positive number and cannot be empty.quantity
must be an integer greater than or equal to 1.- Yup number validation ensures data integrity and prevents invalid numeric inputs.
Yup Boolean Validation
Yup booleans allow you to validate true/false values in JavaScript or TypeScript objects. They are often used for checkboxes, toggle switches, or flags in forms and applications.
Using Yup boolean validation, developers can ensure that fields expecting a true/false value are consistent and optionally provide default values or required checks.
import * as yup from 'yup';
const settingsSchema = yup.object({
newsletter: yup.boolean().required("Newsletter subscription must be specified"),
termsAccepted: yup.boolean().oneOf([true], "You must accept the terms and conditions"),
});
Explanation:
newsletter
is validated as a boolean and must be provided.termsAccepted
ensures the user explicitly agrees (true) before submission.- Yup boolean validation can also handle default values using
.default(false)
for unchecked states.
Yup Enum Validation
Yup enums allow you to restrict a field to a predefined set of values, ensuring that only valid options are accepted. This is especially useful for dropdowns, select inputs, or fields with controlled vocabularies, such as user roles, status flags, or categories.
Using Yup enum validation, developers can prevent invalid entries and maintain consistent data across applications.
import * as yup from 'yup';
const userSchema = yup.object({
role: yup.string()
.oneOf(["admin", "editor", "viewer"], "Role must be one of admin, editor, or viewer")
.required("Role is required"),
});
Explanation:
role
is defined as a string that must match one of the allowed values..oneOf()
enforces the enum-like restriction, accepting only"admin"
,"editor"
, or"viewer"
..required()
ensures that the field cannot be empty.
Yup Metadata
Yup metadata allows you to attach additional information to a schema without affecting the validation itself. This can include descriptions, labels, hints, or custom flags that can be used by forms, UI components, or other tools to enhance functionality.
Using Yup metadata, developers can make schemas more informative and self-descriptive, which is especially helpful in larger projects or dynamic form generators.
import * as yup from 'yup';
const productSchema = yup.object({
name: yup.string().required(),
price: yup.number().positive().required(),
}).meta({ label: "Product Schema", description: "Schema for validating product data" });
Explanation:
- The
.meta()
is attached to the entireproductSchema
object, not a single field. - You can store labels, descriptions, or custom info for UI or documentation purposes.
- This doesn’t affect validation — it’s extra information accessible via
schema.describe()
or by libraries that read metadata.
Conclusion
Yup is a powerful and flexible schema validation library for JavaScript and TypeScript, providing a consistent way to enforce rules for strings, numbers, booleans, arrays, objects, enums, and metadata. By using Yup schema validation, developers can ensure that data is accurate, predictable, and safe before it reaches the backend or gets processed in the application.
Whether you are handling simple form fields or complex nested objects, Yup offers a declarative, chainable API that makes validations readable and maintainable.
By mastering Yup, you can reduce errors, improve user experience, and maintain consistent data structures, making your applications more reliable and developer-friendly.
For developers familiar with Zod schema validation, Yup offers a similarly flexible and declarative approach for validating JavaScript and TypeScript data structures.