typescriptnestjsnestdtoclass-validator

Why Class-validator doesn't process fields without a decorator? | Nest js


I wrote a dto for my endpoint, but ran into the fact that it doesn't work correctly, if one of the fields the class-validator is supposed to handle doesn't have a decorator, it stops being checked at all, even though I need it to be mandatory.

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 above code I tried to process the incoming data, but the problem is that the class-validator on unparses not the permission, with its contents, not the secondErrorExample, which I added to make it easier for you to understand my problem

I would like to point out that I used @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 have not found a solution to this problem myself


Solution

  • Because you have to Type decorator on to permission property. If you want to validate Object ( ex. Permission ), you have to convert the value of the Permission Object to instance of that class. This conversion process is required for the class-validator to execute the verification rules defined for each property within the permission class.

    export class AddProjectRolesDto {
        @IsNumber()
        userId: number
    
        @IsNumber()
        projectId: number
    
        Type(() => Permission)
        permission: Permission
    
        secondErrorExample: any
    }
    

    With this approach, you can solve such that problem