jsonschema vs ajv vs joi vs yup vs z-schema
JSON and Object Validation Libraries for JavaScript
jsonschemaajvjoiyupz-schemaSimilar Packages:

JSON and Object Validation Libraries for JavaScript

ajv, jsonschema, and z-schema are validators based on the official JSON Schema specification, ideal for validating structured data like API payloads against a standard contract. joi and yup use a builder pattern to define object schemas in code, offering a more developer-friendly experience for application logic and form validation. While the first group focuses on strict adherence to the JSON Schema standard, the second group prioritizes developer experience and integration with frontend frameworks like React.

Npm Package Weekly Downloads Trend

3 Years

Github Stars Ranking

Stat Detail

Package
Downloads
Stars
Size
Issues
Publish
License
jsonschema3,186,6491,87583.5 kB762 years agoMIT
ajv014,8631.03 MB3916 months agoMIT
joi021,1641.89 MB2045 days agoBSD-3-Clause
yup023,656270 kB267a year agoMIT
z-schema03491.27 MB313 days agoMIT

JSON and Object Validation: ajv vs joi vs jsonschema vs yup vs z-schema

Validating data is a critical part of building reliable JavaScript applications. Whether you are checking API payloads on the server or ensuring form inputs are correct on the client, you need tools that are accurate and easy to maintain. The five packages here — ajv, joi, jsonschema, yup, and z-schema — solve this problem but take two very different approaches. Let's break down how they work and when to use each one.

📐 Schema Definition: Standard JSON vs Code Builders

The biggest split is how you define what valid data looks like. ajv, jsonschema, and z-schema use the official JSON Schema standard. This means your validation rules are just data objects, which can be shared across different languages. joi and yup use a builder pattern where you write JavaScript code to describe the rules.

ajv uses a standard JSON Schema object.

// ajv: JSON Schema definition
const schema = {
  type: "object",
  properties: {
    email: { type: "string", format: "email" }
  },
  required: ["email"]
};

joi uses a chainable JavaScript API.

// joi: Builder pattern
const schema = Joi.object({
  email: Joi.string().email().required()
});

jsonschema uses a standard JSON Schema object.

// jsonschema: JSON Schema definition
const schema = {
  type: "object",
  properties: {
    email: { type: "string", format: "email" }
  },
  required: ["email"]
};

yup uses a chainable JavaScript API similar to Joi.

// yup: Builder pattern
const schema = yup.object({
  email: yup.string().email().required()
});

z-schema uses a standard JSON Schema object.

// z-schema: JSON Schema definition
const schema = {
  type: "object",
  properties: {
    email: { type: "string", format: "email" }
  },
  required: ["email"]
};

⚡ Validation Execution: Compiling vs Direct Calls

Performance often depends on how the library processes the schema. ajv compiles schemas into functions for speed. Others interpret the schema every time or use different caching strategies.

ajv compiles the schema once for high performance.

// ajv: Compile then validate
const ajv = new Ajv();
const validate = ajv.compile(schema);
const valid = validate(data);

joi validates directly using the schema object.

// joi: Direct validation
const { error, value } = schema.validate(data);

jsonschema validates directly with a helper function.

// jsonschema: Direct validation
const result = validator.validate(data, schema);
const valid = result.valid;

yup validates asynchronously by default.

// yup: Async validation
const valid = await schema.isValid(data);

z-schema validates directly using an instance.

// z-schema: Direct validation
const zSchema = new ZSchema();
const valid = zSchema.validate(data, schema);

🚨 Error Handling: Detailed Reports vs Simple Booleans

When validation fails, you need clear messages to show users or log for debugging. Some libraries return rich error objects, while others require extra steps to get details.

ajv stores errors on the instance after validation.

// ajv: Access errors from instance
if (!validate(data)) {
  console.log(validate.errors);
}

joi returns errors in the result object.

// joi: Errors in result
const { error } = schema.validate(data);
if (error) console.log(error.details);

jsonschema returns errors in the result object.

// jsonschema: Errors in result
const result = validator.validate(data, schema);
if (!result.valid) console.log(result.errors);

yup throws errors or returns them via catch.

// yup: Catch validation errors
try {
  await schema.validate(data);
} catch (err) {
  console.log(err.errors);
}

z-schema provides errors via a getter method.

// z-schema: Get last errors
if (!valid) {
  console.log(zSchema.getLastErrors());
}

🌐 Environment Support: Node vs Browser

Not all libraries work everywhere out of the box. Some are built for Node.js servers, while others are designed to run in the browser bundle.

ajv works in both but requires bundling for browsers.

// ajv: Universal but needs bundling
import Ajv from "ajv";
// Works in Node and Webpack/Vite bundles

joi is primarily for Node.js environments.

// joi: Node.js focused
const Joi = require("joi");
// Browser support requires community builds

jsonschema is lightweight and works in browsers easily.

// jsonschema: Browser friendly
import { Validator } from "jsonschema";
// No heavy dependencies

yup is designed for browser-based React apps.

// yup: Frontend focused
import * as yup from "yup";
// Optimized for bundle size in web apps

z-schema works in both but is heavier.

// z-schema: Universal
import ZSchema from "z-schema";
// Can be bundled for web use

🤝 Similarities: Shared Ground Between Libraries

Despite the differences in approach, these libraries share core goals and capabilities.

1. 🔒 Type Checking

  • All five libraries verify data types like strings, numbers, and booleans.
  • They prevent type-related bugs before data enters your system.
// All support basic type checks
// ajv/jsonschema/z-schema: { type: "number" }
// joi/yup: Joi.number() / yup.number()

2. ✅ Required Fields

  • Every package allows you to mark fields as mandatory.
  • Missing required data triggers a validation error.
// All support required checks
// ajv/jsonschema/z-schema: "required": ["name"]
// joi/yup: .required()

3. 🔗 Nested Objects

  • Complex data structures with nested objects are supported by all.
  • You can validate deep paths in your data.
// All support nesting
// ajv/jsonschema/z-schema: properties: { user: { type: "object" ... } }
// joi/yup: Joi.object({ user: Joi.object() })

4. 📝 Custom Rules

  • You can add custom logic when built-in rules are not enough.
  • This allows for business-specific validation needs.
// All support custom logic
// ajv: addKeyword
// joi: custom()
// yup: test()
// jsonschema/z-schema: custom format or validation

📊 Summary: Key Features

Featureajvjoijsonschemayupz-schema
Schema StyleJSON SchemaBuilderJSON SchemaBuilderJSON Schema
Primary UseAPI ValidationBackend LogicSimple ValidationFrontend FormsLegacy/Specific
CompilationYes (Fast)NoNoNoNo
Async SupportLimitedYesNoYes (Native)Limited
Browser ReadyVia BundleLimitedYesYesVia Bundle

🆚 Summary: Architecture Differences

CategoryJSON Schema Group (ajv, jsonschema, z-schema)Object Schema Group (joi, yup)
DefinitionDeclarative JSON objectsImperative JavaScript code
PortabilityHigh (Language agnostic)Low (JS specific)
FlexibilityStrict to specHigh (Custom logic easy)
Learning CurveHigher (Learn spec)Lower (Intuitive API)

💡 The Big Picture

ajv is the performance king for JSON Schema — use it for high-traffic API validation where standards matter.

joi is the backend workhorse — use it for Node.js services that need powerful data coercion and complex rules.

jsonschema is the lightweight option — use it for simple scripts or environments where you want zero fuss.

yup is the frontend favorite — use it for React forms where async validation and error messages are key.

z-schema is the legacy choice — use it only if you are maintaining older systems that already rely on it.

Final Thought: The choice comes down to where your data lives. If you are sharing schemas between backend and frontend, stick with JSON Schema (ajv). If you are building a React form or a Node API with complex logic, the builder pattern (yup or joi) will save you time.

How to Choose: jsonschema vs ajv vs joi vs yup vs z-schema

  • jsonschema:

    Choose jsonschema if you need a simple, dependency-free implementation of JSON Schema validation that runs easily in both Node and browser environments without complex build steps. It is suitable for smaller projects that require standard compliance without extra features.

  • ajv:

    Choose ajv if you need the fastest JSON Schema validator with support for the latest draft versions and custom keywords. It is the industry standard for validating API requests and responses in Node.js environments where performance and spec compliance matter most.

  • joi:

    Choose joi if you want a robust, feature-rich object validator for Node.js backends or shared validation logic. It excels at complex data transformation and coercion, making it ideal for sanitizing input before it reaches your business logic.

  • yup:

    Choose yup if you are building React forms and need tight integration with libraries like Formik or React Hook Form. Its chainable API and built-in support for asynchronous validation make it the top choice for client-side form state management.

  • z-schema:

    Choose z-schema if you are maintaining a legacy system that already depends on it or need a specific JSON Schema validator with remote reference loading built-in. For new projects, consider ajv instead due to more active maintenance and better performance.

README for jsonschema

Build Status

jsonschema

JSON schema validator, which is designed to be fast and simple to use. JSON Schema versions through draft-07 are fully supported.

Contributing & bugs

Please fork the repository, make the changes in your fork and include tests. Once you're done making changes, send in a pull request.

Bug reports

Please include a test which shows why the code fails.

Usage

Simple

Simple object validation using JSON schemas.

var Validator = require('jsonschema').Validator;
var v = new Validator();
var instance = 4;
var schema = {"type": "number"};
console.log(v.validate(instance, schema));

Even simpler

var validate = require('jsonschema').validate;
console.log(validate(4, {"type": "number"}));

Complex example, with split schemas and references

var Validator = require('jsonschema').Validator;
var v = new Validator();

// Address, to be embedded on Person
var addressSchema = {
  "id": "/SimpleAddress",
  "type": "object",
  "properties": {
    "lines": {
      "type": "array",
      "items": {"type": "string"}
    },
    "zip": {"type": "string"},
    "city": {"type": "string"},
    "country": {"type": "string"}
  },
  "required": ["country"]
};

// Person
var schema = {
  "id": "/SimplePerson",
  "type": "object",
  "properties": {
    "name": {"type": "string"},
    "address": {"$ref": "/SimpleAddress"},
    "votes": {"type": "integer", "minimum": 1}
  }
};

var p = {
  "name": "Barack Obama",
  "address": {
    "lines": [ "1600 Pennsylvania Avenue Northwest" ],
    "zip": "DC 20500",
    "city": "Washington",
    "country": "USA"
  },
  "votes": "lots"
};

v.addSchema(addressSchema, '/SimpleAddress');
console.log(v.validate(p, schema));

Returned ValidatorResult object, will show this example is NOT valid since: "votes": "lots" is not an integer.

Example for Array schema

var arraySchema = {
        "type": "array",
        "items": {
            "properties": {
                "name": { "type": "string" },
                "lastname": { "type": "string" }
            },
            "required": ["name", "lastname"]
        }
    }

For a comprehensive, annotated example illustrating all possible validation options, see examples/all.js

Features

Definitions

All schema definitions are supported, $schema is ignored.

Types

All types are supported

Handling undefined

undefined is not a value known to JSON, and by default, the validator treats it as if it is not invalid. i.e., it will return valid.

var res = validate(undefined, {type: 'string'});
res.valid // true

This behavior may be changed with the "required" option:

var res = validate(undefined, {type: 'string'}, {required: true});
res.valid // false

Formats

Disabling the format keyword.

You may disable format validation by providing disableFormat: true to the validator options.

String Formats

All formats are supported, phone numbers are expected to follow the E.123 standard.

Custom Formats

You may add your own custom format functions. Format functions accept the input being validated and return a boolean value. If the returned value is true, then validation succeeds. If the returned value is false, then validation fails.

  • Formats added to Validator.prototype.customFormats do not affect previously instantiated Validators. This is to prevent validator instances from being altered once created. It is conceivable that multiple validators may be created to handle multiple schemas with different formats in a program.
  • Formats added to validator.customFormats affect only that Validator instance.

Here is an example that uses custom formats:

Validator.prototype.customFormats.myFormat = function(input) {
  return input === 'myFormat';
};

var validator = new Validator();
validator.validate('myFormat', {type: 'string', format: 'myFormat'}).valid; // true
validator.validate('foo', {type: 'string', format: 'myFormat'}).valid; // false

Results

By default, results will be returned in a ValidatorResult object with the following properties:

  • instance: any.
  • schema: Schema.
  • errors: ValidationError[].
  • valid: boolean.

Each item in errors is a ValidationError with the following properties:

  • path: array. An array of property keys or array offsets, indicating where inside objects or arrays the instance was found.
  • property: string. Describes the property path. Starts with instance, and is delimited with a dot (.).
  • message: string. A human-readable message for debugging use. Provided in English and subject to change.
  • schema: object. The schema containing the keyword that failed
  • instance: any. The instance that failed
  • name: string. The keyword within the schema that failed.
  • argument: any. Provides information about the keyword that failed.

The validator can be configured to throw in the event of a validation error:

  • If the throwFirst option is set, the validator will terminate validation at the first encountered error and throw a ValidatorResultError object.

  • If the throwAll option is set, the validator will throw a ValidatorResultError object after the entire instance has been validated.

  • If the throwError option is set, it will throw at the first encountered validation error (like throwFirst), but the ValidationError object itself will be thrown. Note that, despite the name, this does not inherit from Error like ValidatorResultError does.

The ValidatorResultError object has the same properties as ValidatorResult and additionally inherits from Error.

"nestedErrors" option

When oneOf or anyOf validations fail, errors that caused any of the sub-schemas referenced therein to fail are normally suppressed, because it is not necessary to fix all of them. And in the case of oneOf, it would itself be an error to fix all of the listed errors.

This behavior may be configured with options.nestedErrors. If truthy, it will emit all the errors from the subschemas. This option may be useful when troubleshooting validation errors in complex schemas:

var schema = {
  oneOf: [
    { type: 'string', minLength: 32, maxLength: 32 },
    { type: 'string', maxLength: 16 },
    { type: 'number' },
  ]
};
var validator = new Validator();
var result = validator.validate('This string is 28 chars long', schema, {nestedErrors: true});

// result.toString() reads out:
// 0: instance does not meet minimum length of 32
// 1: instance does not meet maximum length of 16
// 2: instance is not of a type(s) number
// 3: instance is not exactly one from [subschema 0],[subschema 1],[subschema 2]

Localizing Error Messages

To provide localized, human-readable errors, use the name string as a translation key. Feel free to open an issue for support relating to localizing error messages. For example:

var localized = result.errors.map(function(err){
  return localeService.translate(err.name);
});

Custom keywords

Specify your own JSON Schema keywords with the validator.attributes property:

validator.attributes.contains = function validateContains(instance, schema, options, ctx) {
  if(typeof instance !== 'string') return;
  if(typeof schema.contains !== 'string') throw new jsonschema.SchemaError('"contains" expects a string', schema);
  if(instance.indexOf(schema.contains)<0){
    return 'does not contain the string ' + JSON.stringify(schema.contains);
  }
}
var result = validator.validate("I am an instance", { type:"string", contains: "I am" });
// result.valid === true;

The instance passes validation if the function returns nothing. A single validation error is produced if the function returns a string. Any number of errors (maybe none at all) may be returned by passing a ValidatorResult object, which may be used like so:

  var result = new ValidatorResult(instance, schema, options, ctx);
  while(someErrorCondition()){
    result.addError('fails some validation test');
  }
  return result;

Dereferencing schemas

Sometimes you may want to download schemas from remote sources, like a database, or over HTTP. When importing a schema, unknown references are inserted into the validator.unresolvedRefs Array. Asynchronously shift elements off this array and import them:

var Validator = require('jsonschema').Validator;
var v = new Validator();
v.addSchema(initialSchema);
function importNextSchema(){
  var nextSchema = v.unresolvedRefs.shift();
  if(!nextSchema){ done(); return; }
  databaseGet(nextSchema, function(schema){
    v.addSchema(schema);
    importNextSchema();
  });
}
importNextSchema();

Disallowing unknown attributes

Sometimes you may want to disallow unknown attributes passed in the body of the request, in order to disallow those unknown attributes before the validation of the body, you need to set additionalProperties to false.

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Accounting Resource - Add Item",
  "type": "object",
  "additionalProperties": false,
  "properties": {
      "itemNumber": {
          "type":"string"
      },
      "title": {
          "type":"string"
      },
      "description": {
          "type":"string"
      }
  },
  "required": [
      "itemNumber",
      "title",
      "description"
  ]
}

Default base URI

Schemas should typically have an id with an absolute, full URI. However if the schema you are using contains only relative URI references, the base option will be used to resolve these.

This following example would throw a SchemaError if the base option were unset:

var result = validate(["Name"], {
  id: "/schema.json",
  type: "array",
  items: { $ref: "http://example.com/schema.json#/definitions/item" },
  definitions: {
    item: { type: "string" },
  },
}, { base: 'http://example.com/' });

Rewrite Hook

The rewrite option lets you change the value of an instance after it has successfully been validated. This will mutate the instance passed to the validate function. This can be useful for unmarshalling data and parsing it into native instances, such as changing a string to a Date instance.

The rewrite option accepts a function with the following arguments:

  • instance: any
  • schema: object
  • options: object
  • ctx: object
  • return value: any new value for the instance

The value may be removed by returning undefined. If you don't want to change the value, call return instance.

Here is an example that can convert a property expecting a date into a Date instance:

const schema = {
  properties: {
    date: {id: 'http://example.com/date', type: 'string'},
  },
};

const value = {
  date: '2020-09-30T23:39:27.060Z',
};

function unmarshall(instance, schema){
  if(schema.id === 'http://example.com/date'){
    return new Date(instance);
  }
  return instance;
}

const v = new Validator();
const res = v.validate(value, schema, {rewrite: unmarshall});

assert(res.instance.date instanceof Date);

Pre-Property Validation Hook

If some processing of properties is required prior to validation a function may be passed via the options parameter of the validate function. For example, say you needed to perform type coercion for some properties:

// See examples/coercion.js
function preValidateProperty(object, key, schema, options, ctx) {
  var value = object[key];
  if (typeof value === 'undefined') return;

  // Test if the schema declares a type, but the type keyword fails validation
  if (schema.type && validator.attributes.type.call(validator, value, schema, options, ctx.makeChild(schema, key))) {
    // If the type is "number" but the instance is not a number, cast it
    if(schema.type==='number' && typeof value!=='number'){
      object[key] = parseFloat(value);
      return;
    }
    // If the type is "string" but the instance is not a string, cast it
    if(schema.type==='string' && typeof value!=='string'){
      object[key] = String(value).toString();
      return;
    }
  }
};

// And now, to actually perform validation with the coercion hook!
v.validate(instance, schema, { preValidateProperty });

Skip validation of certain keywords

Use the "skipAttributes" option to skip validation of certain keywords. Provide an array of keywords to ignore.

For skipping the "format" keyword, see the disableFormat option.

Fail on unknown keywords

By default, JSON Schema is supposed to ignore unknown schema keywords.

You can change this behavior to require that all keywords used in a schema have a defined behavior, by using setting the "allowUnknownAttributes" option to false.

This example will throw a SchemaError:

var schema = {
  type: "string",
  format: "email",
  example: "foo",
};
var result = validate("Name", schema, { allowUnknownAttributes: false });

Tests

Uses JSON Schema Test Suite as well as our own tests. You'll need to update and init the git submodules:

git submodule update --init
npm test

Contributions

This library would not be possible without the valuable contributions by:

  • Austin Wright

... and many others!

License

jsonschema is licensed under MIT license.

Copyright (C) 2012-2019 Tom de Grunt <tom@degrunt.nl>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.