Exploring the Implementation of Validation Pipe in class-validator

I am currently exploring how to effectively utilize my validation pipe in combination with class-validator on an API call.

My DTO is decorated with class-validator decorators and is performing as anticipated. However, I am interested in utilizing the 'skipMissingProperties' feature to bypass validation for non-existent properties (such as 'name' in the provided screenshots).

My goal is to create a straightforward DTO that utilizes various decorators and skips validation for properties that are not included.

Regrettably, it appears that my implementation of skipMissingProperties is incorrect because even when this option is set, validation errors still occur within the DTO.

How can I effectively use the skipMissingProperties option of the validation-pipe alongside class-validator decorators for properties that are present?

In the code snippet below, if I send an update request with parameters excluding 'name', the class validator generates errors at the DTO level.

Screenshot of Validation Pipe on Controller

Screenshot of UpdateViewDTO's decorators

API Controller Endpoint:

@Put(':viewId')
public async updateView(
    @Req() request: RequestExtended,
    @Param('viewId') viewId: string,
    @Body(new ValidationPipe({ skipMissingProperties: true })) updateView: UpdateViewDto)
    : Promise<View> {

    // Perform API operations    

}

UpdateViewDTO:

export class UpdateViewDto {
@IsString()
@MinLength(1, {
    message: LanguageElements.VIEW_NAME_REQUIRED_ERROR_MSG,
})
@MaxLength(50, {
    message: LanguageElements.VIEW_NAME_TOO_LONG_ERROR_MSG,
})
public readonly name?: string;

// Other properties 
}

Answer №1

To implement skipping missing properties in your main.ts, you simply need to include skipMissingProperties: true within the ValidationPipe configuration.


  app.useGlobalPipes(
    new ValidationPipe({
      skipMissingProperties: true,
      exceptionFactory: (errors: ValidationError[]) => {
        return new BadRequestException(errors[0].constraints);
      },
    }),
  );

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

The DOM is not displaying child elements

I am currently looping through an array of objects to generate elements within the Navbar. Despite running the program, I am not able to see these elements being displayed in the DOM, and I am unsure of the reason for this issue. This is the code snippet ...

Guide on placing the initial ListView Item at the bottom of the page

I am currently developing a chat user interface and wondering if there is a way to always display the first ListView Item at the bottom of the screen. The item in question is a text message, so each time a new message is sent, it should appear at the bot ...

Description: TypeScript type that derives from the third constructor parameter of a generic function

How can I determine the type of constructor props for a generic type? Take a look at this example. type PatchableProps<T> = T extends { [k: string | number]: any } ? { [Key in keyof T]: PatchableProps<T[Key]> } : T | Patch export class ...

What could be causing the lack of updates in my shared service across all components?

I have implemented an Angular2 app where I am initializing an authentication service called LocalStorage which I want to be accessible across all my components: bootstrap(AppComponent, [ ROUTER_PROVIDERS, LocalStorage ]); The definition of the Lo ...

Exporting a Middleware member is essential for defining Koa middleware type definitions

Currently utilizing KoA with Typescript and incorporating the KoA middleware KoA-static and KoA-bodyparser. Ensuring that I have installed the type definition packages @types/koa, @types/koa-bodyparser, and @types/koa-static. However, upon running tsc, enc ...

Generating a date without including the time

I recently started working with React (Typescript) and I am trying to display a date from the database without including the time. Here is my Interface: interface Games { g_Id: number; g_Title: string; g_Genre: string; g_Plattform: string; g_ReleaseDate: ...

Finding the specific index of an element in the code has proven challenging, as it consistently returns a value of -1

const index = this.List.findIndex((item:any) => { return item.NAME === result.NAME; }); The index is consistently returning -1 even when the element is found in the List. ...

Error message: Issue with TypeScript and cleave.js - 'rawValue' property is not found on type 'EventTarget & HTMLInputElement'

I am encountering an error with the onChange event while implementing cleave in typescript. TypeScript is throwing an error indicating that 'rawValue' is not present in event.target. Here is my code: import React, { useCallback, useState, useEff ...

How can I customize a Vue component slot in Storybook 8.0.6 using Vue 3.4 and Typescript to display various subcomponents within a story?

Incorporating a variety of sub-components into my Vue 3 component based on context is proving to be a challenge. Utilizing slots seems to be the solution in Vue 3, but I'm struggling to make it work within Storybook 8, which I'm using to showcase ...

Invalid component prop provided to ButtonBase in Material UI. Ensure that the children prop is correctly rendered in this custom component

Forgive me for asking a basic question, as I am not the most proficient frontend developer and have searched extensively online. Whenever I inspect my frontend application in Chrome, I keep encountering this error. (3) Material-UI: The component prop pro ...

Using Element as a type parameter in a React/Typescript function

In my React project using Typescript, I am working on creating a generic collection. The current setup is as follows: class List<T> { constructor(data: any){...} } This code allows me to create a list of a specific type. My goal is to perform a ...

Tips for syncing the state data stored in local storage across all tabs with Ngxs state management

After converting the state data to base64 format using the Ngxs state management library, I am saving it. While I can retrieve all data across different tabs, any changes made in one tab do not automatically sync with other tabs. A tab refresh is required ...

The TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Issue with Typescript and MaterialUI: Module 'csstype' not found or its type declarations

As I set up a new project with Vite, I encountered a perplexing issue when running tsc that resulted in 784 errors related to MUI being unable to locate the csstype module. Here is an example of the error: node_modules/@mui/styled-engine/index.d.ts:1:22 - ...

Issue with TypeScript problemMatcher "$tsc-watch" not actively monitoring files in VSCode

I'm attempting to avoid the necessity of using watch: true in my tsconfig.json setup. Despite utilizing VSCode's tasks with the default problem matcher $tsc-watch, I am encountering an issue where tsc is not running in watch mode during the buil ...

What is the correct way to interpret JSON data received from an Ajax response?

Here is the code snippet that I used: axios.get(url).then(result => { this.setState({ list: result.data, }); }) .catch(e => { console.log("Some error occurred", e); }); The constructor in my code looks like this: constructor(pro ...

Is it possible to activate every function within a prototype?

When presented with a class structure as demonstrated below, I am able to iterate through all its PropertyNames using console.log. class Security { constructor(param: ParamType) { this.method1(param); ... this.methodN(param); } method1(p ...

Enhance the express request to include the user parameter for the passport

I am currently utilizing Passport for authentication in an Express application. This authenticates the user and sets it on the Express response. As I am using TypeScript, trying to set the request type to Request in the route definitions results in an erro ...

Calling a function outside of the constructor

Is there a different way to invoke a function from a service class without doing it in the constructor? I attempted to call the function outside of the constructor, but I wasn't able to get the result of ShowDanger from Toast.service.ts For example: ...

Incorporate ES6 Promise directly into Typescript for enhanced Protractor/WebDriverJS ControlFlow capabilities

Currently, I am incorporating external code in my Protractor tests that yield ES6 Promises. I had the intention of chaining these promises using a ControlFlow, but I encountered a type error during Typescript compilation. Within the test: import {browse ...