When utilizing express-validator 7.0.1, I encounter an issue trying to access the path
field. The error message indicates that "Property 'path' does not exist on type 'ValidationError'.:
import express, { Request, Response } from "express";
import { check, validationResult } from "express-validator";
import { save } from "./UserService";
const router = express.Router();
type ValidationResultError = {
[string: string]: [string];
};
router.post(
"/api/1.0/users",
check("username").notEmpty().withMessage("Username cannot be null"),
check("email").notEmpty().withMessage("E-mail cannot be null"),
async (req: Request, res: Response) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
const validationErrors: ValidationResultError = {};
errors
.array()
.forEach((error) => (validationErrors[error.path] = error.msg)); // error is here
return res.status(400).send({ validationErrors: validationErrors });
}
await save(req.body);
return res.send({ message: "User Created" });
}
);
The code snippet above displays how it appears in the editor.
While examining the source code and iterating through the errors
array, I decided to log the error
object in the console:
...
errors.array().forEach((error) => console.log(error));
...
In the console output, I noticed that each object contained a path
field:
{
type: 'field',
value: null,
msg: 'Username cannot be null',
path: 'username',
location: 'body'
}
{
type: 'field',
value: null,
msg: 'E-mail cannot be null',
path: 'email',
location: 'body'
}
However, despite seeing the path
field, I was only able to access the msg
and type
fields, while the others remained inaccessible:
I am unsure of how to resolve this issue.