简体   繁体   中英

Express validator fails to validate data correctly

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM