The 'path' property is not found on the 'ValidationError' type when using express-validator version 7.0.1

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.

Answer №1

Referencing the migration-v6-to-v7#Telling error types apart

The structure of ValidationError type has been updated in TypeScript to now be a discriminated union.

To accurately handle the desired type for formatting or debugging, utilizing a switch statement or if statements may be necessary.

Note that only FieldValidationError includes the path field.

type FieldValidationError = {
  type: 'field';
  location: Location;
  path: string;
  value: any;
  msg: any;
};

For further insights, take a look at the ValidationError documentation

Any validation errors can be identified by examining the type property.

import express from 'express';
import { check, validationResult } from 'express-validator';

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, res) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            const validationErrors: ValidationResultError = {};
            errors.array().forEach((error) => {
                if (error.type === 'field') {
                    // error is FieldValidationError 
                    validationErrors[error.path] = error.msg;
                }
            });
            return res.status(400).send({ validationErrors: validationErrors });
        }
        return res.send({ message: 'User Created' });
    },
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discovering the bottom scroll position in an Angular application

I am working on implementing two buttons on an Angular web page that allow the user to quickly scroll to the top and bottom of the page. However, I want to address a scenario where if the user is already at the very top of the page, the "move up" button sh ...

How can one access DOM elements (getting and setting values) that are nested within an *ngFor loop?

How can I access the <span> and <select> elements in my code template shown below? <div *ngFor="---"> <div> <span></span> <select> <option></option> <option></option> ...

Cross-origin request error persists despite configuring headers on the server. Unable to successfully relocate image to designated directory on the server

I am encountering a CORS error specifically when sending delete requests from Angular to Laravel. Additionally, I am facing issues with moving car model images to the directory during posting, resulting in errors. I have implemented a CORS middleware and a ...

Encountered an error of 'No overload matches this call' while configuring ContextApi alongside useReducer with Typescript

I am currently setting up ContextApi and useReducer with typescript. I am encountering an error with my "issuesInitialState" variable in useReducer, where I receive the following message: No overload matches this call. Overload 1 of 5, '(reducer: ({ ...

Navigating through diverse objects in Typescript

My challenge involves a state object and an update object that will merge with the state object. However, if the update value is null, it should be deleted instead of just combining them using {...a, ...b}. const obj = { other: new Date(), num: 5, ...

The api path is blocking the request from going through

I am encountering an issue while attempting to make a post request using jquery to the '/get_access_token' URL. Unfortunately, the request seems to be stuck in the 'Sending' phase when testing it in Postman. Below, I have included the r ...

Exploring the DynamoDB List Data Type

Currently, I am working on an angular 8 application where I have chosen to store JSON data in a list data type within DynamoDB. Inserting records and querying the table for data has been smooth sailing so far. However, I have run into some challenges when ...

The Gatsby + Typescript project is reporting that the module with the name "*.module.scss" does not have any exported members

I've recently gone through Gatsby's demo project in their documentation (which is long overdue for an update). I've carefully followed the instructions provided here: I've included an index.d.ts file in the /src directory of my project ...

Using Typescript with Vue.js: Defining string array type for @Prop

How can I properly set the type attribute of the @Prop decorator to be Array<string>? Is it feasible? I can only seem to set it as Array without including string as shown below: <script lang="ts"> import { Component, Prop, Vue } from ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

What could be causing the connection failure between my MongoDB and Node.js?

Hello there! This is my first time posting a question on Stack Overflow. I've been attempting to connect my application to MongoDB. Despite successfully connecting to the server, I am facing issues with the MongoDB connection. I have double-checked ...

Encountering an error while trying to import JSON in TypeScript

I am in need of using mock JSON data to test the rendering of my front-end. import MOCK_FAQ from '../../mocks/FAQ.json'; However, when attempting to import the file, I encountered this exception: Cannot find module '../../mocks/FAQ.json&a ...

Persist various models in Mongoose

Starting off with 2 models for this discussion. -Users -Forms A POST route /form-event is set up to send the following fields: first_name, last_name, form: {} first_name and last_name belong to the Users Model, while form belongs to the Forms Model. T ...

Convert expressApp.ts to use the require method in Node.js

I need assistance in converting the "import" statements to node-friendly "require" in the code below. For example: import * as express from 'express'; should become const express = require('express'); I am facing an issue with the lin ...

Empty array is shown in Node's GET request

I have a database stored in mongoDB which contains some data. However, when I try to retrieve this data using a get request in my Node.js code, all I see is an empty array being returned. Below is the server.js code: const app = express() const mongoose = ...

Angular and Firestore, when combined, present a unique challenge as the queries

After upgrading the code of an outdated project to the latest versions of Angular and RxJs, I made every effort to update the code as thoroughly as possible. Here is a link to my previous code However, I am now encountering the issue of receiving undefin ...

Why is it considered an error when an index signature is missing in a type?

Consider the TypeScript code snippet below: type Primitive = undefined | null | boolean | number | string; // A POJO is simply meant to represent a basic object, without any complexities, where the content is unknown. interface POJO { [key: string]: ...

What steps do I need to follow to integrate Polymer CLI v-2.0 with Node.js and Express to develop an application?

After setting up an Express server and installing polymer-cli, I am trying to figure out how to run Polymer code using Express. Any guidance on this? ...

Typescript: Declaring object properties with interfaces

Looking for a solution to create the childTitle property in fooDetail interface by combining two properties from fooParent interface. export interface fooParent { appId: string, appName: string } export interface fooDetail { childTitle: fooParent. ...

Server emitting an array with no elements to the client using the Socket.io protocol

In my app's input box, when I type a message I expect it to be sent to the server and then back to the client to update my UI. Sending messages to the server works fine, but receiving information from the socket.io server seems to be problematic as i ...