Overview
Yup is a JavaScript schema validation library designed for parsing and validating values. It enables developers to define clear, concise schemas for various data types, including strings, numbers, arrays, and objects. These schemas specify the expected structure, data types, and validation rules for application data, helping to maintain data integrity and prevent common errors. Yup's API is designed to be fluent and chainable, allowing for the construction of complex validation rules in a readable manner.
Yup is particularly well-suited for frontend applications, where it is frequently employed for client-side form validation. Its integration with popular React form libraries such as Formik streamlines the process of validating user input against predefined schemas. This client-side validation provides immediate feedback to users, improving the overall user experience by guiding them toward correct data entry before submission.
Beyond the browser, Yup also serves as a backend validation tool in Node.js environments. Developers use it to validate incoming API request bodies, query parameters, and other data payloads, ensuring that data conforms to server-side expectations before processing. This dual utility across both frontend and backend makes Yup a flexible choice for projects requiring consistent data validation logic across the full stack. The library supports both JavaScript and TypeScript, offering type safety for developers working in TypeScript projects by inferring types directly from the defined schemas.
The library's design emphasizes developer experience, providing intuitive methods for common validation scenarios such as required fields, minimum/maximum lengths, email format checks, and custom validation functions. Its open-source nature means it benefits from community contributions and is entirely free to use, making it accessible for projects of all sizes.
Key features
- Schema Definition: Allows developers to define validation schemas for various data types, including strings, numbers, booleans, dates, arrays, and objects, specifying expected structure and types.
- Chained API: Provides a fluent, chainable API for building complex validation rules, enhancing readability and maintainability of schema definitions.
- Type Inference (TypeScript): Integrates with TypeScript to infer types directly from validation schemas, offering type safety and improved developer experience in TypeScript projects.
- Asynchronous Validation: Supports asynchronous validation, enabling checks against databases or external APIs as part of the validation process.
- Custom Validation: Allows the definition of custom validation methods to handle specific business logic not covered by built-in validators.
- Error Messages: Provides flexible options for customizing validation error messages, allowing for localized or more user-friendly feedback.
- Form Library Integration: Designed to integrate with popular frontend form libraries, such as Formik, for streamlined client-side form validation.
- Schema Transformation: Includes methods for transforming values after validation, such as trimming strings or parsing dates.
Pricing
Yup is an entirely free and open-source library, distributed under the MIT License. There are no licensing fees, subscription costs, or usage-based charges associated with its use. Developers can integrate Yup into commercial or open-source projects without incurring direct costs.
| Feature | Cost | Notes |
|---|---|---|
| Core Library | Free | Full access to all validation features |
| Commercial Use | Free | Permitted under MIT License |
| Community Support | Free | Available via GitHub issues and community forums |
Common integrations
- Formik: Yup is frequently used with Formik for React form validation, providing schema-based validation for form fields.
- React Hook Form: Integrates with React Hook Form via a resolver for schema validation, simplifying form state management and validation.
- Express.js: Can be used in Express.js applications for validating incoming request bodies and query parameters, ensuring data conformity on the server-side.
- NestJS: Applicable in NestJS projects for DTO (Data Transfer Object) validation, often integrated with custom pipes.
- Next.js: Utilized in Next.js applications for both client-side form validation and API route validation.
Alternatives
- Zod: A TypeScript-first schema declaration and validation library that focuses on type inference and provides a concise API.
- Joi: A powerful schema description language and validator for JavaScript objects, widely used in Node.js for API validation.
- Valibot: A small, type-safe schema library that emphasizes performance and bundle size, offering a similar declarative API.
- Confidence: A configuration schema validator from the Hapi ecosystem, used for validating application configurations.
- Ajv: A JSON Schema validator that compiles schemas to fast validation functions, often used for validating complex JSON structures.
Getting started
To begin using Yup, install it via npm or yarn:
npm install yup
# or
yarn add yup
Here's a basic example demonstrating how to define a schema for user data and validate an object against it:
import * as yup from 'yup';
// Define a user schema
const userSchema = yup.object({
name: yup.string().required('Name is required').min(2, 'Name must be at least 2 characters'),
age: yup.number().required('Age is required').positive('Age must be a positive number').integer('Age must be an integer'),
email: yup.string().email('Invalid email format').required('Email is required'),
website: yup.string().url('Invalid URL format').nullable(),
friends: yup.array().of(yup.string()).nullable(),
});
// Example data to validate
const validUser = {
name: 'Jane Doe',
age: 30,
email: '[email protected]',
website: 'https://janedoe.com',
friends: ['John', 'Alice']
};
const invalidUser = {
name: 'J',
age: -5,
email: 'invalid-email',
website: 'not-a-url',
friends: [123] // Should be strings
};
// Validate valid user data
userSchema.validate(validUser)
.then(validatedData => {
console.log('Valid user:', validatedData);
})
.catch(error => {
console.error('Validation error for valid user:', error.message);
});
// Validate invalid user data
userSchema.validate(invalidUser, { abortEarly: false }) // abortEarly: false collects all errors
.then(validatedData => {
console.log('Valid user:', validatedData); // This won't be reached
})
.catch(error => {
console.error('Validation errors for invalid user:', error.errors);
/* Expected output (or similar):
[
'Name must be at least 2 characters',
'Age must be a positive number',
'Age must be an integer',
'Invalid email format',
'Invalid URL format',
'friends field has errors'
]
*/
});
// You can also use .isValid for a boolean check
userSchema.isValid(validUser).then(isValid => {
console.log('Is validUser valid?', isValid); // true
});
userSchema.isValid(invalidUser).then(isValid => {
console.log('Is invalidUser valid?', isValid); // false
});
This example defines a schema for a user object with various validation rules, including required fields, minimum length for names, positive integers for age, and email/URL format checks. It then demonstrates how to use .validate() to check data against the schema and catch validation errors, as well as .isValid() for a simple boolean check.