The reason why Class-validator doesn't handle fields that lack a decorator in Nest js

After creating a DTO for my endpoint, I encountered an issue where the class-validator stops checking a field if it doesn't have a decorator assigned to it. Even though I need the field to be mandatory and checked, it gets skipped.

DTO:

import {IsNumber} from 'class-validator';


export class Permission {
    addNewTask: boolean
    updateTask: boolean
    addEmployees: boolean
    updateEmployees: boolean
    addRole: boolean
    updateRole: boolean

}
export class AddProjectRolesDto {
    @IsNumber()
    userId: number

    @IsNumber()
    projectId: number

    permission: Permission

    secondErrorExample: any
}

In the code snippet above, I tried processing incoming data but faced an issue where the class-validator fails to parse both the permission object along with its contents and the secondErrorExample that I added for clarity on my problem.

I want to highlight that I utilized @UsePipes(new ValidationPipe()) in my controller.

Example of an incoming object that passed validation due to an error:

{
    "userId": 1,
    "projectId": 2,
    "permission": {}
}

Unfortunately, I haven't been able to find a solution to this particular issue on my own.

Answer №1

By adding the Type decorator to the permission property, you can properly validate the object (e.g., Permission) by converting its value into an instance of that class. This conversion is necessary for class-validator to enforce the validation rules specified for each property within the permission class.

export class AddProjectRolesDto {
    @IsNumber()
    userId: number

    @IsNumber()
    projectId: number

    Type(() => Permission)
    permission: Permission

    secondErrorExample: any
}

Implementing this approach will help resolve the issue mentioned above.

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

Could you explain the significance of the ^ symbol preceding a software version number?

Considering updating a package in my application, specifically the "@types/react-router-dom" from version "4.3.1" to "5.0.0". However, I'm hesitant as it is a large project and I don't want to risk breaking anything. While reviewing the package. ...

Nested Tagged Union Types in Typescript

Imagine having the following types (syntax similar to Elm/Haskell): type Reply = LoginReply | LogoutReply type LoginReply = LoginSucceeded | AlreadyLoggedIn String When trying to represent this in Typescript using discriminated unions, a challenge arises ...

Unable to get the Angular Formly select option to bind

I'm currently working on binding formly select type options with the following code: fieldGroup: [ { key: 'TimeOffTypeID', type: 'select', className: 'flex-40 padding-10', templateOptions ...

Ways to apply color conditions to table rows based on table data values?

I am using ngFor to create a table from two arrays in Angular typescript. <tr *ngFor="let e of lis1; let k=index"> <td>{{e}} </td> <td>{{lis2[k]}}</td> </tr> The resulting table l ...

Changing the type of a `let` variable will revert back to its original type when it is passed to a closure

Can you explain why foobar reverts to type Foobar when referenced from the function passed to filter in the code snippet below? type Foo = { type: "foo", foo: number }; type Bar = { type: "bar", bar: number }; type Foobar = Foo | Bar; ...

What is the method to determine the size of an array of objects where each object contains its own internal array?

Here is the data that I have: var a=[ { name: "time", Details:[ {value:"month",checked:true,id:1} ] }, { name: "product", Details:[ {value: ...

Performing an action within the Redux RTK API Slice

Is it feasible to trigger an action from a different reducer within the API Slice of Redux RTK? Let's say I have this scenario: getSomething: builder.query<SomeProps, void>({ query: () => ({ url: "...", ...

When object signatures match exactly, TypeScript issues a warning

I am facing an issue with typescript while trying to use my own custom type from express' types. When I attempt to pass 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' as a parameter of type 'Context&a ...

Combatting repetitive code through the use of Redux toolkit and actions

My code is currently long and repetitive. I realize that using helper functions would help me cut it down and make it more maintainable and readable. As a React beginner, I have a question: Should I implement most of this logic with helper functions in a s ...

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

Is there a way to retrieve the ReturnType<T> for all methods within a class, even if the ReturnType<T> and its usage appear to be static?

After extensively reviewing the documentation on typescript at https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypet, I have come across two instances of ReturnType<T> mentioned. However, these instances appear to be statically ...

Converting nested arrays to objects via JSON transformation

I am faced with a nested JSON array structure like this: Parent: { Child1: [ {name:'grandchild1', value:'abc', checked:true}, {name:'grandchild2', value:'pqr', checked:false} ], Ch ...

the process of altering properties in vue js

After running my Vue file, I encountered the following console error. As someone new to Vue programming, I'm attempting to utilize a Syncfusion UI component to display a grid. Prop being mutated: "hierarchyPrintMode" I am unsure where to add the comp ...

`Unresponsiveness in updating bound property after change in Angular2 child property`

Having trouble with my custom directive and ngOnChanges() not firing when changing a child property of the input. my.component.ts import {Component} from 'angular2/core'; import {MyDirective} from './my.directive'; @Component({ d ...

I am trying to figure out how to send a One Signal notification from my Ionic app using the One Signal REST API. I have reviewed the documentation, but I am still unable to understand it

Is there a way to send a one signal notification from my ionic app using the one signal API? I have reviewed the documentation but am having trouble with it. While I have set up the service and it is functional, I can only manually send notifications thr ...

What is the best way to transfer my static files to the desired output directory in a TypeScript Express application?

I am attempting to transfer my static files from the input directory to the output directory using Express. I found guidance in this tutorial, which utilized shell.js for copying static files. The code responsible for this operation is located in CopyAsse ...

Error received from Http Get request

I am currently facing an issue with my Angular component that is supposed to make a simple HTTP Get request: this.http.get<any>('http://localhost:80/userservice/login', { params: { username: this.model.username, password: this.model.passwo ...

Reinforced.Typings does not generate fully qualified names (FQN) for types when UseModules is set to true or false

Overview: Within my solution, I have two projects: ProjA and ProjB. In ProjA, I've defined a custom RTConfigure method to streamline the configuration process for translating C# to TypeScript using the Reinforced.Typings tool. Meanwhile, ProjB houses ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...

The object literal can only define existing properties, and the property 'allAwsRegions' is not found in the 'IResolvable' type

Currently, I am working with the AWS-CDK and attempting to set up a Config Aggregator to combine the storage of configuration logs from all regions. Instead of using an account as the source, I have opted for a region due to restrictions on configuring org ...