Express Joi Validations

0.1.0 · maintenance · verified Wed Apr 22

express-joi-validations is an Express.js middleware package designed to streamline request validation using the Joi schema validation library. Currently at version 0.1.0, it provides a flexible mechanism to validate various parts of an incoming HTTP request, including headers, URL parameters, query strings, and the request body. While its last publish was over two years ago (as of May 2024), suggesting a maintenance-only status rather than active development, it offers both a consolidated validation middleware for multiple request parts and individual helper functions (e.g., `validateBody`, `validateParams`) for more granular control. Key differentiators include its explicit handling of validated data through `request.validationValues` and the ability to optionally overwrite the original request data or throw errors for integration with asynchronous error handling. This allows developers to strictly enforce data integrity at the API layer.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up an Express server with multiple Joi validations for a PUT request, including headers, parameters, and body, and integrates a basic error handling middleware.

import express, { Request, Response, NextFunction } from 'express';
import { Joi, validateHeaders, validateParams, validateBody, expressJoiValidations } from 'express-joi-validations';

const app = express();
app.use(express.json()); // Required to parse JSON request bodies

// Optionally configure global settings for all validations
app.use(expressJoiValidations({ throwErrors: true, overwriteRequest: false }));

const userToken = Joi.object({
  authorization: Joi.string().regex(/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_.+/=]*$/).required(),
});

const postId = Joi.object({
  id: Joi.string().hex().length(24).required(),
});

const postBody = Joi.object({
  title: Joi.string().required().trim().min(5),
  content: Joi.string().required().trim().min(10),
  tags: Joi.array().items(Joi.string()).optional()
});

// Example route with chained validations
app.put(
  '/posts/:id',
  validateHeaders(userToken),
  validateParams(postId),
  validateBody(postBody, { allowUnknown: false }), // Joi options can be passed per validator
  (req: Request, res: Response) => {
    // If throwErrors is true, an error handler middleware will catch validation errors.
    // Otherwise, validation results (errors, values) are on req.validationErrors and req.validationValues
    const validatedData = (req as any).validationValues; // Cast to 'any' or extend Request type if not using `overwriteRequest`
    res.status(200).json({ message: 'Post updated successfully', data: validatedData });
  }
);

// Global error handler for thrown validation errors (if throwErrors: true)
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
  if (err && err.error && err.error.isJoi) {
    // A Joi validation error
    return res.status(400).json({ type: err.type, message: err.error.toString() });
  }
  next(err); // Pass on to other error handlers
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

view raw JSON →