Home > Software design >  Express validator fails to validate data correctly
Express validator fails to validate data correctly

Time:08-30

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 ?

CodePudding user response:

You will need a body parser middleware set up before handling the body fields. For instance, try setting your route like this (if you're sending the body as json):

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

CodePudding user response:

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);
  • Related