question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Running validations imperatively

See original GitHub issue

I followed the example below to create a validation middleware using a validation chain:

example:

// can be reused by many routes
const validate = async validations => {
  return (req, res, next) => {
    await Promise.all(validations.map(validation => validation.run(req)));

    const errors = validationResult(req);
    if (errors.isEmpty()) {
      return next();
    }

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

app.post('/api/create-user', validate([
  body('email').isEmail(),
  body('password').isLength({ min: 6 })
]), async (req, res, next) => {
  // request is guaranteed to not have any validation errors.
  const user = await User.create({ ... });
});

my code (using typescript): /models/order.ts

// order validation chain
import { checkSchema, ValidationChain } from 'express-validator';

export const schema: ValidationChain[] = checkSchema({
 orderNumber: {
    isString: true,
    errorMessage: 'Order number is required'
  }
});
import { ValidationChain, validationResult } from 'express-validator';
import { Router, Request, Response, NextFunction } from 'express';

import * as orderModel from '../models/order';

const router = Router();

type RouteHandler = (
  req: Request,
  res: Response,
  next: NextFunction
) => Promise<void>;

// validation middleware
const validate = (validations: ValidationChain[]): RouteHandler => {
  return async (
    request: Request,
    response: Response,
    next: NextFunction
  ): Promise<void> => {
    await Promise.all(
      validations.map(
        (val: ValidationChain): Promise<Context> => val.run(request)
      )
    );

    const result = validationResult(request);

   // result.isEmpty() is always true
    if (!result.isEmpty()) {
      response.status(422).json();
      return;
    }
    next();
  };
};

// route handler using the validation middleware
router.post('/', validate(orderModel.schema), ordersController.createOrder);

The issue is that when awaiting for all the validations in:

await Promise.all(
      validations.map(
        (val: ValidationChain): Promise<Context> => val.run(request)
      )
    );

The request object is not being affected and then when using const result = validationResult(request); No errors are attached to the object. In other words, result.isEmpty() is always true.

I modified the code a little bit just to see what all the promises resolved:

const data = await Promise.all(
      validations.map(
        (val: ValidationChain): Promise<Context> => val.run(request)
      )
    );

And all the errors are inside the data variable. To be specific data is an array of Context objects, and those objects are holding the errors. The issue is that when running validations imperatively the request object is not being affected.

Im using express-validator version 6.0.1

Thanks for your help.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:6 (3 by maintainers)

github_iconTop GitHub Comments

2reactions
krzysztof-ocommented, Jun 28, 2019

I confirm the fix is working for me 👍

0reactions
lock[bot]commented, Aug 27, 2019

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Running validations imperatively - express-validator
Running validations imperatively ... express-validator favors the declarative way of doing things that express middlewares bring. This means most of the APIs look ......
Read more >
express - Run a oneOf validation imperatively? - Stack Overflow
I was looking into running the validations imperatively as indicated in Running validations imperatively [docs] for code readability purposes. ...
Read more >
Imperative Code-Based Validation - .NET Framework
Imperative code-based validation provides a simple way for an activity to provide validation about itself, and is available for activities ...
Read more >
A Clean Approach to Using Express Validator
In this article, I'll be showing how the validation above can be made more readable and easier to maintain. Step 1. Create a...
Read more >
Form Data Validation in Node.js with express-validator
It is imperative to carry out server-side validation when building ... When done, we will install the following dependencies by running the ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found