ajv vs joi vs typanion vs yup vs zod
Data Validation Libraries
ajvjoitypanionyupzodSimilar Packages:

Data Validation Libraries

Data validation libraries in JavaScript are tools that help ensure the data being processed in an application meets specific criteria or rules. These libraries are essential for validating user input, API requests, and any data that needs to conform to a particular structure or format. They provide a way to define validation schemas, check data against these schemas, and handle errors when the data is invalid. This process helps improve data integrity, enhance security by preventing malicious input, and provide better feedback to users or developers when data does not meet the expected standards. Popular data validation libraries include ajv, joi, yup, zod, and typanion, each with its unique features and use cases.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
ajv014,6281.03 MB31715 days agoMIT
joi021,201557 kB1903 months agoBSD-3-Clause
typanion0275133 kB193 years agoMIT
yup023,690270 kB2405 months agoMIT
zod042,0014.34 MB254a month agoMIT

Feature Comparison: ajv vs joi vs typanion vs yup vs zod

TypeScript Support

  • ajv:

    ajv provides TypeScript definitions, but its primary focus is on JSON Schema validation rather than TypeScript type inference. It is more suited for projects where JSON Schema compliance is critical.

  • joi:

    joi has good TypeScript support, but it was originally designed for JavaScript. Recent versions have improved type definitions, making it more type-safe and easier to use in TypeScript projects.

  • typanion:

    typanion is designed with TypeScript in mind, offering first-class support for TypeScript types and type safety. It leverages TypeScript's type system to provide more accurate type inference and validation.

  • yup:

    yup offers excellent TypeScript support, with well-defined types and interfaces that make it easy to use in TypeScript projects. It provides good type inference for schemas and validation functions.

  • zod:

    zod is a TypeScript-first library that provides the best type inference among these options. It is designed to work seamlessly with TypeScript, making it ideal for projects that prioritize type safety and inference.

Asynchronous Validation

  • ajv:

    ajv supports asynchronous validation out of the box, especially for validating data against schemas that include asynchronous constraints or custom keywords.

  • joi:

    joi supports asynchronous validation, allowing validators to return promises. This is useful for scenarios like validating data against external sources or performing async checks.

  • typanion:

    typanion supports asynchronous validation, making it suitable for scenarios where validation requires async operations, such as checking values against a database or an API.

  • yup:

    yup has built-in support for asynchronous validation, allowing you to define async validation rules and handle promises in your validation logic.

  • zod:

    zod supports asynchronous validation, particularly for validating data with async functions or promises. It allows for flexible integration of async validation logic.

Error Handling

  • ajv:

    ajv provides detailed error messages and supports custom error formatting. It allows you to access validation errors in a structured way, making it easier to handle and display them.

  • joi:

    joi offers comprehensive error handling with detailed messages. It provides a rich error object that includes information about the validation failure, making it easy to customize error handling and messaging.

  • typanion:

    typanion provides structured error handling that integrates with TypeScript's type system. It allows for clear and consistent error reporting, making it easier to handle validation errors in a type-safe manner.

  • yup:

    yup provides clear and customizable error messages. It allows you to access validation errors in a structured format, making it easy to display errors in user interfaces or handle them programmatically.

  • zod:

    zod offers structured error handling with detailed error messages. It provides a clear API for accessing validation errors, making it easy to integrate with UI frameworks and handle errors effectively.

Schema Definition

  • ajv:

    ajv uses JSON Schema for schema definition, which is a standardized format for describing the structure of JSON data. This makes it highly interoperable and suitable for projects that require strict schema compliance.

  • joi:

    joi uses a fluent API for schema definition, allowing for expressive and readable validation rules. It is highly customizable and supports complex nested validations, making it versatile for various use cases.

  • typanion:

    typanion uses a TypeScript-based approach for schema definition, leveraging TypeScript's type system to enforce validation rules. This makes it particularly suited for TypeScript projects where type safety is a priority.

  • yup:

    yup uses a fluent API similar to joi for defining schemas. It is designed to be simple and intuitive, making it easy to create both simple and complex validation rules.

  • zod:

    zod uses a declarative, TypeScript-first approach for schema definition. It is designed to be simple and intuitive, with a focus on type safety and minimal boilerplate code.

Ease of Use: Code Examples

  • ajv:

    JSON Schema Validation with ajv

    const Ajv = require('ajv');
    const ajv = new Ajv();
    const validate = ajv.compile({
      type: 'object',
      properties: {
        name: { type: 'string' },
        age: { type: 'integer', minimum: 0 }
      },
      required: ['name', 'age'],
      additionalProperties: false
    });
    const valid = validate({ name: 'John', age: 30 });
    if (!valid) console.log(validate.errors);
    
  • joi:

    Object Validation with joi

    const Joi = require('joi');
    const schema = Joi.object({
      name: Joi.string().required(),
      age: Joi.number().integer().min(0).required()
    });
    const { error, value } = schema.validate({ name: 'John', age: 30 });
    if (error) console.log(error.details);
    
  • typanion:

    Type-Safe Validation with typanion

    import { createValidator } from 'typanion';
    const validate = createValidator({
      name: (value) => typeof value === 'string',
      age: (value) => typeof value === 'number' && value >= 0
    });
    const isValid = validate({ name: 'John', age: 30 });
    if (!isValid) console.error('Validation failed');
    
  • yup:

    Yup Validation Example

    const yup = require('yup');
    const schema = yup.object().shape({
      name: yup.string().required(),
      age: yup.number().integer().min(0).required()
    });
    schema.validate({ name: 'John', age: 30 })
      .then((value) => console.log('Valid:', value))
      .catch((err) => console.log('Error:', err.errors));
    
  • zod:

    Zod Validation Example

    import { z } from 'zod';
    const schema = z.object({
      name: z.string(),
      age: z.number().min(0)
    });
    const result = schema.safeParse({ name: 'John', age: 30 });
    if (!result.success) {
      console.error(result.error.format());
    } else {
      console.log('Valid:', result.data);
    }
    

How to Choose: ajv vs joi vs typanion vs yup vs zod

  • ajv:

    Choose ajv if you need a fast, standards-compliant JSON Schema validator that supports asynchronous validation and custom keywords. It is ideal for projects that require strict adherence to JSON Schema specifications and high performance.

  • joi:

    Select joi if you want a powerful and expressive schema description language for validating JavaScript objects. It offers a rich set of built-in validators, supports asynchronous validation, and is highly customizable, making it suitable for complex validation scenarios.

  • typanion:

    Opt for typanion if you are looking for a TypeScript-first validation library that leverages TypeScript's type system to provide type-safe validation. It is designed for developers who want to enforce types and validation rules in a way that integrates seamlessly with TypeScript's type checking.

  • yup:

    Use yup if you need a schema builder for runtime value parsing and validation, especially in React applications. It is inspired by joi but is more lightweight and has a simpler API, making it easy to use for both simple and complex validations.

  • zod:

    Choose zod if you prefer a TypeScript-first schema declaration and validation library that provides static type inference. It is designed to be simple and intuitive, with a focus on type safety and minimal boilerplate, making it a great choice for modern TypeScript projects.

README for ajv

Ajv logo

 

Ajv JSON schema validator

The fastest JSON validator for Node.js and browser.

Supports JSON Schema draft-04/06/07/2019-09/2020-12 (draft-04 support requires ajv-draft-04 package) and JSON Type Definition RFC8927.

build npm npm downloads Coverage Status SimpleX Gitter GitHub Sponsors

Ajv sponsors

Mozilla

Microsoft

RetoolTideliftSimpleX

Contributing

More than 100 people contributed to Ajv, and we would love to have you join the development. We welcome implementing new features that will benefit many users and ideas to improve our documentation.

Please review Contributing guidelines and Code components.

Documentation

All documentation is available on the Ajv website.

Some useful site links:

Please sponsor Ajv development

Since I asked to support Ajv development 40 people and 6 organizations contributed via GitHub and OpenCollective - this support helped receiving the MOSS grant!

Your continuing support is very important - the funds will be used to develop and maintain Ajv once the next major version is released.

Please sponsor Ajv via:

Thank you.

Open Collective sponsors

Performance

Ajv generates code to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization.

Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks:

Performance of different validators by json-schema-benchmark:

performance

Features

Install

To install version 8:

npm install ajv

Getting started

Try it in the Node.js REPL: https://runkit.com/npm/ajv

In JavaScript:

// or ESM/TypeScript import
import Ajv from "ajv"
// Node.js require:
const Ajv = require("ajv")

const ajv = new Ajv() // options can be passed, e.g. {allErrors: true}

const schema = {
  type: "object",
  properties: {
    foo: {type: "integer"},
    bar: {type: "string"},
  },
  required: ["foo"],
  additionalProperties: false,
}

const data = {
  foo: 1,
  bar: "abc",
}

const validate = ajv.compile(schema)
const valid = validate(data)
if (!valid) console.log(validate.errors)

Learn how to use Ajv and see more examples in the Guide: getting started

Changes history

See https://github.com/ajv-validator/ajv/releases

Please note: Changes in version 8.0.0

Version 7.0.0

Version 6.0.0.

Code of conduct

Please review and follow the Code of conduct.

Please report any unacceptable behaviour to ajv.validator@gmail.com - it will be reviewed by the project team.

Security contact

To report a security vulnerability, please use the Tidelift security contact. Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues.

Open-source software support

Ajv is a part of Tidelift subscription - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers.

License

MIT