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.
npm install dat-middlewareVerified import paths — ran on the pinned version, not inferred.
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.
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.
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.
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.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.
Ensure the client sends all parameters specified by `.require()` in the request body (e.g., JSON), query string, or URL parameters.
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`).
Adjust the client input to satisfy the custom validation logic defined by the `.validate()` middleware for that parameter.
Ensure the string value for the parameter precisely matches the regular expression pattern specified in the `.matches()` middleware.