Kay
Kay

Reputation: 19660

express-validator extracting validation into separate file

I am trying to validate some input using express validator but i have a different setup than one in the documentation.

Im validating if the body.payload is not null

this.validator.document

   public document = async (req: Request, res: Response, next: NextFunction) => {
        check("payload").exists({ checkNull: true });
        try {
            validationResult(req).throw();
            next();
          } catch (err) {
            res.status(422).json({ errors: err.mapped() });
        }
    }

this.controller.document

 public document = async (req: Request, res: Response): Promise<any> => {

        const errors = validationResult(req);
        if (!errors.isEmpty()) {
          return res.status(422).json({ errors: errors.array() });
       }
}

documentRoute

     this.router.post("/:id/document",
            this.jwtGuard,
            this.validator.document,
            this.controller.document);

im aware check is a middleware in itself, so how do i handle this inside my existing validator function that may have some other validation before it.

At the moment this does not work, even tho payload is set to null. It should catch the error and return a 422 response but it is not.

Upvotes: 1

Views: 3538

Answers (1)

Leo
Leo

Reputation: 751

in validator.document:

public document = () => check("payload").exists({ checkNull: true });

in documentRoute:

this.router.post("/:id/document",
        this.jwtGuard,
        this.validator.document(), // notice the parentheses
        this.controller.document);

Update: If you want to handle the errors in validator.document, you need to call check middleware before it when declaring the route:

this.router.post("/:id/document",
    this.jwtGuard,
    check("payload").exists({ checkNull: true }),
    this.validator.document,
    this.controller.document);

And in validator.document:

public document = async (req: Request, res: Response, next: NextFunction) => {
   const errors = validationResult(req);
   if (!errors.isEmpty()) {
      return res.status(422).json({ errors: errors.array() });
   }
}

Update 2: If you have multiple check operations and does not want to bloat your route definition, I suggest you use schema validation.

Upvotes: 2

Related Questions