-1

I have endpoint where I post some data to create a user. I am validating the request body with Joi. But when I post using Postman, validation fails.

Here, something similar to the validation function,

const checkData = (data) => {
    const schema = Joi.object({
        image: Joi.string(),
        greeting: Joi.string().valid("Hello World!", "Welcome").required(),
        email: Joi.string().email().required(),
    });

    return schema.validateAsync(data);
};

Here is the multer setup,

const storage = multer.diskStorage({
    destination: (req, file, callback) => {
        callback(null, "./upload/");
    },
    filename: (req, file, callback) => {
        callback(null, Date.now().toString() + "_" + file.originalname);
    },
});

const fileFilter = (req, file, callback) => {
    if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
        callback(null, true);
    } else {
        callback(null, false);
    }
};

const upload = multer({ storage, fileFilter });

And, here is my route,

router.post("/create/:whatever", upload.single("image"), async (req, res) => {
    try {
        await checkData(req.body);
        res.send(req.params.whatever);
    } catch (err) {
        res.send({ message: err.details[0].message });
    }
});

And the error response I got saying,

{
    "message": "\"email\" must be a valid email"
}

In case you are wondering whether I am sending the email right or not, I am, sending an actual valid email. I am sure missing something here, please let me know.

Hasan
  • 247
  • 7
  • 22
  • 1
    You could try logging `req.body` before the `checkData(...)` call and see what you're getting in the request body – Shadab Dec 23 '20 at 14:02
  • Thanks, should have checked that earlier, turns out, everything is correct but I have extra space at the starting of the email field which is giving me this validation error. – Hasan Dec 23 '20 at 17:15

1 Answers1

0

Actually everything is fine, turns out, in the form data in Postman there was an extra space that I didn't notice. Removing that extra space at the start resolved the validation error.

Hasan
  • 247
  • 7
  • 22