Good Eggs JSON Schema Validator
npm install goodeggs-json-schema-validator
- Common JSON schema and tv4 add-ons for Good Eggs ecosystem.
- Express middleware to validate requests using JSON Schemas.
Common schema add-ons
Adds support for these formats:
- objectid
- date (YYYY-MM-DD)
- date-time (for example, 2014-05-02T12:59:29+00:00)
- time (HH:mm or HH:mm:ss, e.g. 23:04:20)
- email
Simply include the format in your schema:
{"type": "string", "format": "date"}
Express Validation
(Loosely modeled on express-joi-validator.)
When validation fails, uses Boom to wrap errors.
Recommended to use Crashpad for passing those errors to the client.
Methods
All methods return middleware that can be use()
d or included in a route chain.
validateRequest(field, schema, options)
validates schema against property on request objectvalidateResponse(field, schema, options)
validates schema against property on response object
The schema
param should be a JSON Schema,
including properties
, required
, etc. Its type
defaults to object
.
Example
Validate URL params:
var expressValidator = require('goodeggs-json-schema-validator/lib/express');
var crashpad = require('crashpad')
app.use(crashpad());
app.get('/products/:slug',
expressValidator.validateRequest('params', {
type: 'object'
properties: {
'slug': {
type: 'string'
pattern: '^[a-z-]+$'
}
}
}),
function (req, res) {
}
);
If a request is made to /products/INVALID_123
,
it will fail with statusCode 400
and a body containing message
with a description of the error.
Contributing
Please follow our Code of Conduct
when contributing to this project.
$ git clone https://github.com/goodeggs/goodeggs-json-schema-validator && cd goodeggs-json-schema-validator
$ npm install
$ npm test