{"id":17560,"library":"dat-middleware","title":"Express Middleware for Request Validation and Transformation","description":"dat-middleware is an Express.js middleware library that provides a fluent and declarative API for common request data operations. It focuses on validating and transforming `req.body`, `req.query`, and `req.params` against various criteria such as required fields, data types (string, number, array, boolean, object, function), specific class instances (`instanceOf`), and regular expressions (`matches`). Developers can also integrate custom validation logic using the `validate()` method. Upon validation failure, the middleware automatically calls `next()` with a 400 Bad Request error object generated by `spumko/boom`, simplifying error handling. The current stable version is 1.10.4. Given its last update several years ago, it operates primarily in a maintenance mode, offering a stable but not actively developed solution for Express input validation. Its key differentiator is the chaining syntax for defining validation rules directly within the middleware stack.","status":"maintenance","version":"1.10.4","language":"javascript","source_language":"en","source_url":"https://github.com/tjmehta/dat-middleware","tags":["javascript","express","middleware","request","response","body","query","params"],"install":[{"cmd":"npm install dat-middleware","lang":"bash","label":"npm"},{"cmd":"yarn add dat-middleware","lang":"bash","label":"yarn"},{"cmd":"pnpm add dat-middleware","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime dependency for integrating middleware into an Express application.","package":"express"},{"reason":"Used internally for generating standardized HTTP error objects (400 Bad Request) on validation failure. Note: refers to the 'spumko/boom' package, which is an older version of the library now maintained as '@hapi/boom'.","package":"boom"}],"imports":[{"note":"dat-middleware is a CommonJS module and does not natively support ES module imports. Direct ESM usage will require a CommonJS wrapper or bundler configuration.","wrong":"import mw from 'dat-middleware';","symbol":"mw","correct":"const mw = require('dat-middleware');"},{"note":"The Boom error object generator is exposed as a property of the main 'mw' export. The underlying 'spumko/boom' library it uses is deprecated.","wrong":"import { Boom } from 'dat-middleware';","symbol":"Boom","correct":"const Boom = require('dat-middleware').Boom;"},{"note":"The validation chain methods (e.g., `body`, `query`, `params`) are accessed as properties of the main `mw` export.","wrong":"app.use(body('key').require());","symbol":"mw.body() / mw.query() / mw.params()","correct":"app.use(mw.body('key').require());"}],"quickstart":{"code":"var mw = require('dat-middleware');\nvar express = require('express');\nvar app = express();\nvar bodyParser = require('body-parser'); // Needed for req.body\n\napp.use(bodyParser.json()); // To parse JSON bodies\n\n// Custom validation function example: ensures a string is exactly 24 characters\nfunction is24Chars (val) {\n  if (typeof val !== 'string') {\n    return mw.Boom.badRequest('must be a string');\n  }\n  return (val.length !== 24) ?\n    mw.Boom.badRequest('is not 24 characters'):\n    null; // pass\n}\n\n// Define a route that uses dat-middleware for validation and transformation\napp.post('/user',\n  // Require 'name' and 'age' in the request body\n  mw.body('name', 'age').require(),\n  // Ensure 'age' is a number\n  mw.body('age').number(),\n  // Ensure 'id' matches a specific regular expression (e.g., MongoDB ObjectID format)\n  mw.body('id').matches(/^[a-fA-F0-9]{24}$/), \n  // Apply custom validation to 'description'\n  mw.body('description').validate(is24Chars),\n  // If all validations pass, process the request\n  function (req, res) {\n    res.json({\n      message: 'User data validated and processed!',\n      data: req.body\n    });\n  }\n);\n\n// Start the server\nconst PORT = process.env.PORT || 3000;\napp.listen(PORT, () => {\n  console.log(`Server listening on port ${PORT}`);\n  console.log('Test with valid data:');\n  console.log(`  curl -X POST -H \"Content-Type: application/json\" -d '{\"name\":\"John Doe\",\"age\":30,\"id\":\"60c72b2f9c1d44001c8c4e4e\", \"description\": \"This is a 24 char string\"}' http://localhost:${PORT}/user`);\n  console.log('Test with invalid age (not a number):');\n  console.log(`  curl -X POST -H \"Content-Type: application/json\" -d '{\"name\":\"Jane Doe\",\"age\":\"thirty\",\"id\":\"60c72b2f9c1d44001c8c4e4e\", \"description\": \"This is a 24 char string\"}' http://localhost:${PORT}/user`);\n  console.log('Test with missing name:');\n  console.log(`  curl -X POST -H \"Content-Type: application/json\" -d '{\"age\":30,\"id\":\"60c72b2f9c1d44001c8c4e4e\", \"description\": \"This is a 24 char string\"}' http://localhost:${PORT}/user`);\n});","lang":"javascript","description":"This quickstart sets up an Express server with `dat-middleware` to validate request body parameters for a `/user` endpoint, demonstrating required fields, type checks, regex matching, and custom validation."},"warnings":[{"fix":"For Node.js ESM projects, consider using a CommonJS wrapper or a different, modern validation library. For browser builds, ensure your bundler (webpack, rollup) is configured to handle CommonJS modules.","message":"dat-middleware is a CommonJS module and requires explicit configuration (e.g., bundler support or a wrapper) to be used directly in an ES Module-only Node.js environment or browser builds.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Be aware that custom error handling or integration with other Hapi libraries might require adapting to the older Boom version. Consider migrating to a more actively maintained validation library for new projects.","message":"The library internally uses 'spumko/boom' (now '@hapi/boom'), an older version of the Boom error handling library. While functional, it might not be compatible with newer versions of Boom or related Hapi ecosystem tools.","severity":"deprecated","affected_versions":">=1.0.0"},{"fix":"Implement an Express error handling middleware function (e.g., `app.use(function (err, req, res, next) { ... })`) that specifically checks for Boom errors (e.g., `err.isBoom`) to extract status codes and messages correctly.","message":"Error handling relies on Express's standard next(err) mechanism. The errors are Boom objects (HTTP 400). If you have custom error middleware, ensure it can properly interpret and respond to these error types.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"For complex object validation, prefer `validate()` with a custom function that performs structural checks, or use a dedicated schema validation library that offers more robust type and structure validation.","message":"The `instanceOf` validation method relies on JavaScript's prototype chain. This might not behave as expected when dealing with objects passed across different realms (e.g., if objects are deserialized from JSON or come from different Node.js contexts), or if the `Class` constructor is not the exact one used to create the instance.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the client sends all parameters specified by `.require()` in the request body (e.g., JSON), query string, or URL parameters.","cause":"A parameter specified by `.require()` was missing from `req.body`, `req.query`, or `req.params`.","error":"body parameter \"key1\" is required"},{"fix":"Verify that the client sends the specified parameter as a valid JSON array or an array in query string/URL parameters (e.g., `?key1[]=val1&key1[]=val2`).","cause":"A parameter that was expected to be an array type did not receive an array.","error":"body parameter \"key1\" must be an array"},{"fix":"Adjust the client input to satisfy the custom validation logic defined by the `.validate()` middleware for that parameter.","cause":"A custom validation function provided to `.validate()` returned a Boom error because the input value did not meet its specified criteria.","error":"body parameter \"key1\" is not 24 characters"},{"fix":"Ensure the string value for the parameter precisely matches the regular expression pattern specified in the `.matches()` middleware.","cause":"A string parameter did not conform to the regular expression pattern defined in the `.matches()` middleware.","error":"body parameter \"key1\" must match /^hello/"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}