express-joi-validations
Express middleware to validate request (headers, params, query, body) using Joi
Installation
npm i express-joi-validations
Usage
Out of the box
import validate from 'express-joi-validations';
router.put('/posts/:id', validate({ headers: userToken, params: postId, body: postBody }), (request, response) => {
});
With custom settings
import express from 'express';
import { expressJoiValidations } from 'express-joi-validations';
const app = express();
app.use(expressJoiValidations({ validationConfigs }));
Configuration
-
throwErrors (default: false): Define if errors should be thrown (suggested usage with express-async-errors)
-
overwriteRequest (default: false): Define if original request should be overwritten with validated data.
Helper methods
validateBody
import { Joi, validateBody } from 'express-joi-validations';
const postBody = Joi.object({
title: Joi.string().required().trim(),
content: Joi.string().required().trim().min(10),
});
router.post('/posts', validateBody(postBody), postsController.create);
validateParams
import { Joi, validateParams } from 'express-joi-validations';
const postId = Joi.object({
id: Joi.string().hex().length(24),
});
router.get('/posts/:id', validateParams(postId), postsController.detail);
validateQuery
import { Joi, validateQuery } from 'express-joi-validations';
const postQuery = Joi.object({
page: Joi.optional().number().integer().min(1).default(1),
});
router.get('/posts', validateQuery(postQuery), postsController.list);
import { Joi, validateHeaders } from 'express-joi-validations';
const userToken = Joi.object({
authorization: Joi.string().regex(/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*$/),
});
router.delete('/posts/:id', validateHeaders(userToken), postsController.remove);
Chain
import { validateHeaders, validateParams, validateBody } from 'express-joi-validations';
router.put('/posts/:id', validateHeaders(userToken), validateParams(postId), validateBody(postBody), postsController.update);
Joi options
To every function, is possible to add a second parameter to specify custom Joi Options:
router.post('/posts', validateBody(postBody, { allowUnknown: true }), postsController.create);