Node.js Express Form Validation

Validate form data in Node.js Express using express-validator middleware chains, custom sanitizers, grouped error responses, and conditional validation.

JavascriptNodeForm Validation

Code

snippet
import { body, validationResult } from 'express-validator';

export const validateLogin = [
  body('email').isEmail().normalizeEmail(),
  body('password').isLength({ min: 8 }).withMessage('Min 8 chars'),
  (req, res, next) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    next();
  },
];

What to watch for

  • External dependency: express-validator — install it before running the snippet.

Using it

Signature: export const validateLogin =

Import validateLogin and call it from your own module — the snippet is a drop-in helper, not an executable program.

The crux of the implementation is this line:

body('password').isLength({ min: 8 }).withMessage('Min 8 chars'),

One more line that carries real weight:

import { body, validationResult } from 'express-validator';

And the line that closes the loop:

return res.status(400).json({ errors: errors.array() });

Interactive Tools for This Topic

FAQ

Does this require external packages?
Yes — `express-validator`. Add it to your project before running the snippet.