javascript
35 lines · 8 steps
A reusable validation middleware in Express
Turn an express-validator rule schema into a single middleware that validates, formats errors, and exposes clean data.
Explained by
highlit
1const { validationResult, matchedData } = require('express-validator');
2
3function validate(schema) {
4 const runners = schema.map((rule) => rule.run.bind(rule));
5
6 return async (req, res, next) => {
7 await Promise.all(runners.map((run) => run(req)));
8
9 const result = validationResult(req);
10 if (!result.isEmpty()) {
11 return res.status(422).json({
12 error: 'ValidationError',
13 details: result.array().map(({ path, msg, value }) => ({
14 field: path,
15 message: msg,
16 value,
17 })),
18 });
19 }
20
21 req.validated = matchedData(req, { includeOptionals: false });
22 return next();
23 };
24}
25
26const { body } = require('express-validator');
27
28const createUserRules = [
29 body('email').trim().isEmail().withMessage('must be a valid email').normalizeEmail(),
30 body('password').isLength({ min: 8 }).withMessage('must be at least 8 characters'),
31 body('displayName').optional().trim().isLength({ max: 60 }).escape(),
32 body('age').optional().isInt({ min: 13, max: 120 }).toInt(),
33];
34
35module.exports = { validate, createUserRules };
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A middleware factory lets you configure behavior once and reuse it across many routes.
- 2Running all validators with Promise.all validates fields concurrently before checking results.
- 3matchedData gives you only the validated, sanitized fields, keeping raw input out of your handlers.
Related explainers
javascript
import { unstable_cache, revalidateTag } from 'next/cache' import { db } from '@/lib/db' export const getDashboardStats = unstable_cache(
Caching dashboard stats in Next.js
caching
cache-invalidation
tag-based-revalidation
Intermediate
8 steps
java
@Component @Order(Ordered.HIGHEST_PRECEDENCE) public class TenantResolutionFilter extends OncePerRequestFilter {
How a tenant-resolution filter works in Spring
multi-tenancy
servlet-filter
thread-local
Intermediate
8 steps
go
package middleware import ( "compress/gzip"
How gzip HTTP middleware works in Go
middleware
compression
object-pooling
Intermediate
7 steps
php
<?php namespace App\Experiments;
Weighted random selection in PHP
weighted-random
cumulative-sum
sampling
Intermediate
8 steps
javascript
import { Component } from 'react'; import { reportError } from './services/telemetry'; export class ErrorBoundary extends Component {
How a React ErrorBoundary works
error-handling
lifecycle-methods
render-props
Intermediate
8 steps
rust
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::{DecodeError, Engine}; pub fn encode_standard(data: &[u8]) -> String {
Base64 encode and decode in Rust
base64
encoding
error-handling
Beginner
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-reusable-validation-middleware-in-express-explained-javascript-1285/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.