Product
Introducing License Enforcement in Socket
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
express-json-validator-middleware
Advanced tools
An Express middleware to validate requests against JSON Schemas
express.js middleware for validating requests against JSON Schema
Coming from express-jsonschema
? Read our migration notes
Starting with 1.1.0
, this module uses ajv@5
, read their changelog and migration guide here.
express-json-validator-middleware
is being actively maintained.$ npm install express-json-validator-middleware
--save
is no longer necessary as of npm@5
var { Validator, ValidationError } = require('express-json-validator-middleware');
var validator = new Validator({allErrors: true});
var validate = validator.validate;
Validator.validate({
requestProperty: schemaToUse
})
Example: Validate req.body
against bodySchema
app.post('/street/', validate({body: bodySchema}), function(req, res) {
// route code
});
On encountering erroneous data, the validator will call next() with a ValidationError object. It is recommended to setup a general error handler for your app where you will catch ValidationError errors
Example - error thrown for the body
request property
ValidationError {
name: 'JsonSchemaValidationError',
validationErrors: {
body: [AjvError]
}
}
More information on ajv#errors
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var { Validator, ValidationError } = require('express-json-validator-middleware');
// Initialize a Validator instance first
var validator = new Validator({allErrors: true}); // pass in options to the Ajv instance
// Define a shortcut function
var validate = validator.validate;
// Define a JSON Schema
var StreetSchema = {
type: 'object',
required: ['number', 'name', 'type'],
properties: {
number: {
type: 'number'
},
name: {
type: 'string'
},
type: {
type: 'string',
enum: ['Street', 'Avenue', 'Boulevard']
}
}
}
// This route validates req.body against the StreetSchema
app.post('/street/', validate({body: StreetSchema}), function(req, res) {
// At this point req.body has been validated and you can
// begin to execute your application code
});
Sometimes your route may depend on the body
and query
both having a specific format. In this example we use body
and query
but you can choose to validate any request
properties you like.
var TokenSchema = {
type: 'object', // req.query is of type object
required: ['token'] // req.query.token is required
properties: {
token: { // validate token
type: 'string',
format: 'alphanumeric',
minLength: 10,
maxLength: 10
}
}
}
app.post('/street/', Validator.validate({body: StreetSchema, query: TokenSchema}), function(req, res) {
// application code
});
A valid request must now include a token URL query. Example valid URL: /street/?token=F42G5N5BGC
Instead of passing in a schema object you can also pass in a function that will return a schema. It is useful if you need to generate or alter the schema based on the request object.
Example: loading schema from the database
// Middleware executed before validate function
function loadSchema(req, res, next) {
getSchemaFromDB()
.then((schema) => {
req.schema = schema;
next();
})
.catch(next);
}
// function that returns a schema object
function getSchema(req) {
// return the schema from the previous middleware or the default schema
return req.schema || DefaultSchema;
}
app.post('/street/', loadSchema, Validator.validate({body: getSchema}), function(req, res) {
// route code
});
Ajv custom keywords must be defined before 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 });
// route handlers with validate()
More info on custom keywords: ajv#customs-keywords
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 // ajv instance
Tests are written using Mocha & Chai
npm install
npm test
express-jsonschema
In express-jsonschema
, you could define a required property in two ways. Ajv only supports one way of doing this.
// CORRECT
{
type: 'object',
properties: {
foo: {
type: 'string'
}
},
required: ['foo'] // <-- correct way
}
// WRONG
{
type: 'object',
properties: {
foo: {
type: 'string',
required: true // nono way
}
}
}
FAQs
An Express middleware to validate requests against JSON Schemas
The npm package express-json-validator-middleware receives a total of 15,995 weekly downloads. As such, express-json-validator-middleware popularity was classified as popular.
We found that express-json-validator-middleware demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Ensure open-source compliance with Socket’s License Enforcement Beta. Set up your License Policy and secure your software!
Product
We're launching a new set of license analysis and compliance features for analyzing, managing, and complying with licenses across a range of supported languages and ecosystems.
Product
We're excited to introduce Socket Optimize, a powerful CLI command to secure open source dependencies with tested, optimized package overrides.