Data validation libraries are designed for validating data at runtime, so it throws or returns detailed runtime errors for you or your end users. This is especially useful in situations like accepting arbitrary input in a REST or GraphQL API. It can even be used to validate internal data structures at runtime when needed.
Instead of having your data validation and sanitization logic written as lengthy code, you can declare the requirements to your data with concise easy to read cross-platform schemas and validate the data as soon as it arrives to your application.
Zod (31k ⭐) — A TypeScript-first schema declaration and validation library. Zod is designed to be as developer-friendly as possible. The goal is to eliminate duplicative type declarations. With Zod, you declare a validator once and Zod will automatically infer the static TypeScript type. It’s easy to compose simpler types into complex data structures.
Valibot (5.3k ⭐) — Validate unknown data with Valibot, the open source schema library with bundle size, type safety and developer experience in mind. Due to the modular design of our API the bundle size starts at less than 600 bytes.
Joi (20.7k ⭐) — The most powerful schema description language and data validator for JavaScript. Joi lets you describe your data using a simple, intuitive, and readable language. With Joi, you can easily validate and sanitize input data, ensuring that it meets the desired criteria and constraints.
Validator.js (22.7k ⭐) — This library validates and sanitizes strings only, validate all sorts of concerns related to string and convert if possible.
Yup (22.4k ⭐) — Schema builder for runtime value parsing and validation. Define a schema, transform a value to match, assert the shape of an existing value, or both. Yup schema are extremely expressive and allow modeling complex, interdependent validations, or value transformation.
Ajv (13.5k ⭐) — A JSON Schema validator for Node.js and browser, implements full JSON Schema, asynchronous loading of referenced schemas during compilation, etc.
Superstruct (6.9k ⭐) — Makes it easy to define interfaces and then validate JavaScript data against them. Its type annotation API was inspired by Typescript, Flow, Go, and GraphQL, giving it a familiar and easy to understand API.
v8n (4.2k ⭐) — Fluent and simple validation library for use in any context. The API is beautifully readable and allows for easy creation of complex validations in any part of your app. The name v8n is actually derived from the structure of the word “validation”.
Ow (3.8k ⭐) — Function argument validation for humans. Ow has expressive chainable API, lots of built-in validations, supports custom validations, automatic label inference in Node.js, and written in TypeScript.
Typia (4.1k ⭐) — A transformer library, supporting those features: super-fast runtime validators, safe JSON parse and fast stringify, JSON schema generator, and random data generator.
JavaScript object validators typically have some common features that help ensure the validity and integrity of objects:
Data Validation: Object validators often include mechanisms to validate the data contained within an object. This involves checking the type, format, and integrity of the data against predefined rules or constraints. Validators may perform checks such as type checking, length validation, pattern matching, range validation, and more.
Schema Definition: Validators often rely on a schema definition to specify the structure and validation rules for the object. A schema is a blueprint that describes the expected properties, their types, requiredness, and any additional constraints. It serves as a reference for validating objects against the defined schema.
Error Handling: When validation fails, validators typically generate error messages or exceptions to indicate the specific validation issues encountered. These error messages can help developers identify and resolve validation problems more easily. Validators may provide detailed information about the specific property or rule that failed validation.
Custom Rules and Extensions: Object validators may offer the ability to define custom validation rules or extend the existing set of validation rules. This allows developers to tailor the validation process to their specific requirements. Custom rules can be added to perform complex validations or handle unique cases.
Nested Object Validation: JavaScript object validators often support nested object validation. This means that they can recursively validate objects within objects, ensuring the validity of complex data structures. Validators may traverse nested properties and apply validation rules to each level.
Conditional Validation: Validators may support conditional validation, where the validation rules are applied based on certain conditions or dependencies. For example, certain properties may only require validation if another property has a specific value. This feature enhances flexibility and allows for dynamic validation logic.
Extensibility and Integration: Validators can often be integrated with other libraries or frameworks, allowing developers to combine validation capabilities with other functionalities. They may also provide hooks or events that developers can use to extend or customize the validation process further.
Localization and Internationalization: Some validators support localization and internationalization, enabling error messages and validation rules to be translated or adapted to different languages and regional formats. This feature is particularly useful when developing applications with multilingual support.
It’s important to note that specific implementation details and available features may vary depending on the library or framework you’re using to perform object validation in JavaScript.
Schema definitions, are comprised of parsing “transforms” which manipulate inputs into the desired shape and type, “tests”, which make assertions over parsed data. Schema also store a bunch of “metadata”, details about the schema itself, which can be used to improve error messages, build tools that dynamically consume schema, or serialize schema into another format.
import { object, string, number, date, InferType } from 'yup';
let userSchema = object({
name: string().required(),
age: number().required().positive().integer(),
email: string().email(),
website: string().url().nullable(),
createdOn: date().default(() => new Date()),
});
// parse and assert validity
const user = await userSchema.validate(await fetchUser());
A schema’s default is used when casting produces an undefined output value. Because of this, setting a default affects the output type of the schema.
JSON Schema is a specification for describing the structure and validation rules of JSON documents. It provides a standardized way to define the schema for JSON data. JSON Schema is a language-agnostic specification, meaning it can be used with any programming language or platform that supports JSON.
Here is an example of a JSON Schema for a product in a catalog:
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://example.com/product.schema.json",
"title": "Product",
"description": "A product in the catalog",
"type": "object",
"properties": {
"name": {
"description": "The name of the product",
"type": "string"
},
"price": {
"description": "The price of the product",
"type": "number",
"minimum": 0
},
"tags": {
"description": "The tags of the product",
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
}
},
"required": ["name", "price"]
}
JavaScript object validators can leverage JSON Schema to perform validation on JavaScript objects. These validators can use the JSON Schema specification as a guideline to define and enforce the validation rules for JavaScript objects. By adhering to the JSON Schema specification, JavaScript object validators ensure consistency and interoperability in the validation process across different programming languages and platforms.
JSON Schema provides a rich set of validation keywords and features that can be used to define the rules and constraints for validating JavaScript objects. Validators can interpret and apply these JSON Schema keywords to perform data validation on JavaScript objects, checking for properties, types, requiredness, pattern matching, numerical constraints, and more.