api-validation-error-handler
v1.1.0
Published
Error handler middleware for express-validator formatted responses
Downloads
9
Maintainers
Readme
api-validation-error-handler
A clean reusable Express middleware for handling validation errors produced by express-validator, providing unified API responses and localization support. This middleware reduces repeated error handling logic and keeps controllers clean.
📦 Installation
npm install api-validation-error-handleror
yarn add api-validation-error-handler✨ Features
✔ Handles validation errors automatically
✔ Converts errors into key/value structure
✔ Uses standard API response format via express-api-responses
✔ Keeps controllers clean and focused
🚀 Usage
1. Import middleware
import { handleValidationErrors } from "api-validation-error-handler";or using CommonJS:
const { handleValidationErrors } = require("api-validation-error-handler");2. Apply validator and middleware
import express from "express";
import { body } from "express-validator";
import { handleValidationErrors } from "api-validation-error-handler";
const router = express.Router();
router.post(
"/books",
[
body("name")
.notEmpty()
.withMessage((value, { req }) => "Name is required"),
body("price")
.isFloat({ gt: 0 })
.withMessage((value, { req }) => "Price must be greater than 0"),
],
handleValidationErrors(), // 🚨 always after validators
(req, res) => {
res.json({ status: true, message: "Book created successfully" });
}
);
export default router;🎛 Custom Message Key
You can override the returned message:
handleValidationErrors("Input validation error")Example:
router.post(
"/login",
[
body("email")
.isEmail()
.withMessage((v, { req }) => "Invalid email format"),
],
handleValidationErrors("Login validation failed"),
loginController
);📤 Response Format
If validation fails:
{
"statusCode": 400,
"status": false,
"message": "failed to login",
"data": null,
"errors": {
"email": "email address is invalid"
}
}If validation succeeds:
➡ Controller continues normally.
🧠 How It Works
It checks validation errors, formats them, and returns an API response:
- Key = field name
- Value = validation message
Example formatted output:
{
"name": "Name is required",
"price": "Price must be greater than 0"
}📌 Notes & Recommendations
Put this middleware after validation rules
Works with:
body()param()query()
Keeps response structure consistent across the API
🧑💻 Requirements
This package depends on:
- express-validator
- express-api-responses
Ensure they are installed in your project.
🏁 Summary
Use handleValidationErrors() in any route to avoid manually checking validation results and formatting error responses. This middleware is ideal for large-scale Express REST APIs where consistent error handling is required.
📌 For suggestions, improvements, or feature requests—open an issue anytime.
