A JSONSchema validator that uses code generation to be extremely fast.
It passes the entire JSONSchema v4 test suite except for remoteRefs and maxLength/minLength when using unicode surrogate pairs.
Installation
npm install --save is-my-json-valid
Usage
Simply pass a schema to compile it
var validator = require('is-my-json-valid')var validate = validator({ required: true, type: 'object', properties: { hello: { required: true, type: 'string' } }})console.log('should be valid', validate({hello: 'world'}))console.log('should not be valid', validate({}))// get the last list of errors by checking validate.errors// the following will print [{field: 'data.hello', message: 'is required'}]console.log(validate.errors)
You can also pass the schema as a string
var validate = validator('{"type": ... }')
Optionally you can use the require submodule to load a schema from __dirname
var validator = require('is-my-json-valid/require')var validate = validator('my-schema.json')
Custom formats
is-my-json-valid supports the formats specified in JSON schema v4 (such as date-time).
If you want to add your own custom formats pass them as the formats options to the validator
Many popular libraries make it easy to retrieve the failing rule with the schemaPath:
var schemaPath = validate.errors[0].schemaPathvar R = require('ramda')console.log( 'All evaluate to the same thing: ', R.equals( schema.properties.hello, { required: true, type: 'string' }, R.path(schemaPath, schema), require('lodash').get(schema, schemaPath), require('jsonpointer').get(schema, [""].concat(schemaPath))))// All evaluate to the same thing: true
Greedy mode tries to validate as much as possible
By default is-my-json-valid bails on first validation error but when greedy is
set to true it tries to validate as much as possible:
If you know any other relevant benchmarks open a PR and I'll add them.
TypeScript support
This library ships with TypeScript typings. They are still early on and not perfect at the moment, but should hopefully handle the most common cases. If you find anything that doesn't work, please open an issue and we'll try to solve it.
The typings are using unknown and thus require TypeScript 3.0 or later.
Here is a quick sample of usage together with express:
import createError = require('http-errors')import createValidator = require('is-my-json-valid')import { Request, Response, NextFunction } from 'express'const personValidator = createValidator({ type: 'object', properties: { name: { type: 'string' }, age: { type: 'number' }, }, required: [ 'name' ]})export function post (req: Request, res: Response, next: NextFunction) { // Here req.body is typed as: any
As you can see, the typings for is-my-json-valid will contruct an interface from the schema passed in. This allows you to work with your incoming json body in a type safe way.