express-json-validator-middleware
express.js middleware for JSON schema validation.

This package is a work in progress - feedback is heavily appreciated
Based heavily on https://github.com/trainiac/express-jsonschema. A big thank you to @trainiac for the original package!
- Performance - We use ajv instead of JSONSchema, offering a significant performance boost.
- Newer JSON Schema Standard - Using ajv under the hood allows us to support JSON Schema v5 proposal.
- Active Maintenance -
express-json-validator-middleware
is being actively maintained by @JouzaLoL
Why validate with JSON schemas?
- Simple - JSON schemas are a simple and expressive way to describe a data structure.
- Standard - JSON schemas are not specific to Javascript. In fact, they are used just about everywhere.
- Fail-Fast - Catch errors early in your logic, evading confusing errors later.
- Separate Validation - Keep your routes clean. Validation logic doesn't need to be defined in your route handlers.
- Error Messaging - Ajv provides you with rich error objects that can easily be transformed into human-readable format.
- Documentation - Creating a JSON Schema is another way of documenting your application.
Installation
$ npm install express-json-validator-middleware --save-dev
Getting started
- Install the module
- Require the module
var { Validator, ValidationError } = require('express-json-validator-middleware');
- Initialize a Validator instance, passing in an optional options object for the Ajv instance. Ajv options can be found here: ajv#options
var validator = new Validator({allErrors: true});
- Optional - Define a shortcut function. Bind is necessary here in order to pass
this
correctly
var validate = validator.validate.bind(validator);
- Use the function as an Express middleware, passing in an options object of the following format:
validate({
request_property: schema_to_use
})
Example: Validate req.body against BodySchema
app.post('/street/', validate({body: BodySchema}), function(req, res) {
});
- The validator will either do nothing, if the data is valid, or call next() with a ValidationError as a parameter, if the data is found to be erroneous.
Error handling
On encountering erroneous data, the validator will call next with a ValidationError object.
It is recommended to setup a general error handler for your express app where you will catch errors of type ValidationError
Error example (pseudocode):
ValidationError {
name: 'JsonSchemaValidationError',
validationErrors: {
body: [AjvError]
}
}
Information on Ajv errors can be found here: ajv#errors
Example Express app
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var { Validator, ValidationError } = require('express-json-validator-middleware');
var validator = new Validator({allErrors: true});
var validate = validator.validate.bind(validator);
var StreetSchema = {
type: 'object',
required: ['number, name, type'],
properties: {
number: {
type: 'number'
},
name: {
type: 'string'
},
type: {
type: 'string',
enum: ['Street', 'Avenue', 'Boulevard']
}
}
}
app.post('/street/', validate({body: StreetSchema}), function(req, res) {
});
Validating multiple request properties
Sometimes your route may depend on the body
and query
both having a specific format. In this example I use body
and query
but you can choose to validate any request
properties you'd like.
var TokenSchema = {
type: 'object',
required: ['token']
properties: {
token: {
type: 'string',
format: 'alphanumeric',
minLength: 10,
maxLength: 10
}
}
}
app.post('/street/', validate({body: StreetSchema, query: TokenSchema}), function(req, res) {
});
A valid request must now include a token URL query. Example valid URL: /street/?token=F42G5N5BGC
Custom keywords
Ajv supports custom keywords out of the box. They must be defined only after you initialize a Validator, but before you any validate() middleware. Example:
var { Validator, ValidationError } = require('express-json-validator-middleware');
var validator = new Validator({allErrors: true});
validator.ajv.addKeyword('constant', { validate: function (schema, data) {
return typeof schema == 'object' && schema !== null
? deepEqual(schema, data)
: schema === data;
}, errors: false });
More info on custom keywords: ajv#customs-keywords
Ajv instance
The Ajv instance can be accessed via validator.ajv.
var { Validator, ValidationError } = require('express-json-validator-middleware');
var validator = new Validator({allErrors: true});
validator.ajv
Tests
npm install
npm test
More documentation on JSON schemas
Notes
In express-jsonschema
, you could define a required property in two ways. Ajv only supports the latter.
{
type: 'object',
properties: {
foo: {
type: 'string',
required: true
}
}
}
{
type: 'object',
properties: {
foo: {
type: 'string'
},
required: ['foo']
}
}