The Complete Guide to Yup Schema Validation
Form validation is one of the most critical parts of any web application—and that's where Yup shines. Yup is a powerful JavaScript schema builder used primarily for validating object shapes. It plays a crucial role in modern form handling libraries like Formik, React Hook Form, and more.
In this guide, we’ll explore how Yup helps developers validate user inputs, create reusable schemas, and ensure data correctness throughout the app.
What is Yup?
Yup is a JavaScript schema builder that lets you define and validate object structures. Inspired by Joi and JSON Schema, Yup offers a declarative way to describe validations and enforce types at runtime.
Whether you're validating a simple login form or a deeply nested object, Yup provides an expressive and extensible API to handle all common use cases.
Defining a Basic Schema
Here's a simple example of a Yup schema for a login form:
import * as yup from 'yup';
const loginSchema = yup.object({
email: yup.string().email().required(),
password: yup.string().min(8).required(),
});
In the above example, the schema enforces:
A valid email format
A password with at least 8 characters
This is often used with form libraries like Formik and React Hook Form for real-time validation.
Common Yup Validation Types
Yup offers validation for a wide range of data types:
String validation:
yup.string().required()Number validation:
yup.number().positive().integer()Boolean validation:
yup.boolean()Array validation:
yup.array().of(...)Date validation:
yup.date().min(...)Object validation:
yup.object({ ... })Mixed schema: for custom or unknown types
These types let you define rules such as .required(), .min(), .max(), .matches(), and more.
Nested Object Validation
Yup also supports nested validation, which is useful for complex form structures:
const profileSchema = yup.object({
user: yup.object({
name: yup.string().required(),
age: yup.number().min(18),
}),
});
This ensures that all fields inside user follow their respective validation rules.
Conditional Validation
Yup allows fields to change validation behavior based on other values using .when():
const schema = yup.object({
isCompany: yup.boolean(),
companyName: yup.string().when('isCompany', {
is: true,
then: (schema) => schema.required(),
otherwise: (schema) => schema.notRequired(),
}),
});
This is helpful when certain fields are only required under specific conditions.
Custom Validation Messages
To improve user experience, Yup allows you to define custom error messages:
yup.string().required('This field is required').email('Invalid email format');
This makes the validation feedback more user-friendly and precise.
Async Validation
You can even handle asynchronous validations, such as checking for email uniqueness via API:
yup.string().test(
'checkEmailUnique',
'This email is already taken',
async (value) => await isEmailAvailable(value)
);
This opens the door to more dynamic validation logic.
Transform and Preprocess Values
Using .transform(), Yup can preprocess values before validation. For example:
yup.string().transform((value) => value.trim());
This is useful to normalize inputs (like trimming spaces) before applying validation rules.
Integration with Form Libraries
Yup pairs naturally with form libraries:
Formik with Yup: Built-in support for validationSchema
React Hook Form with Yup: via
@hookform/resolvers/yupRedux Form and Yup: using custom validation functions
This allows you to manage form state and validation seamlessly.
Reusable Schemas
You can compose and reuse Yup schemas across your app:
const nameSchema = yup.string().required();
const ageSchema = yup.number().min(18);
const userSchema = yup.object({
name: nameSchema,
age: ageSchema,
});
This promotes DRY principles and modular validation.
Schema Shape vs Field-level Validation
Yup supports both full object validation (using .object().shape()) and individual field-level validation, making it flexible for different validation strategies.
Validating on Submit vs On Change
Depending on your form UX, you can validate Yup schemas on:
Field blur events
Input changes
Form submission
Yup doesn’t enforce when validation occurs; your form library typically controls that.
Final Thoughts
Yup schema validation brings a declarative, intuitive approach to validating user input in JavaScript and TypeScript applications. Its integration with popular form libraries and rich feature set—including conditional logic, nested validation, and async tests—makes it a top choice for developers.