Express validator fails to validate data correctly

Issue

Hello i am using the latest version of express-validator to validate my requests body, the problem is when i am using notEmpty() or not().isEmpty() it always shows an error with prsonalized message i putted "text field is required" even when the text field is not empty
this is my validator.js file

import { body } from "express-validator";

export const checkPost = () => {
  return [
    body("text")
    .trim()
    .notEmpty()
    .withMessage("text field is required")
  
 ];
};

 

this is my route.js :

router.post("/", checkPost(), uploadImg, createPost);

and this is my controller.js

export const createPost = async (req, res) => {
 try {
   const errors = validationResult(req);

   if (!errors.isEmpty()) {
     return res.json({ errors: errors.array() });
   } ....

this is the response i get :

{
"errors": [
    {
        "value": "",
        "msg": "text field is required",
        "param": "text",
        "location": "body"
    }
 ]
}

Can anyone help me please ?

Solution

After many hours of search i found that the express-validator middleware should be called after the usage of multer so changing my route this way solved the problem

router.post("/",uploadImg, checkPost(), createPost);

Answered By – Ghost

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published