ItsJay
ItsJay

Reputation: 198

validating multi-layers nested objects in nestjs

Im trying to use classValidator decorators in nestJs to validate incomming request of the following type

{
    address: string
    location: { 
        longitude: string, 
        latitude : string
    }
}

. the problem is that its just limited to one layer of nestedObject . the one below works

class ProjectLocation { 
    @IsString()
    address: string; 
}

export class CreateProjectDto {

    @ValidateNested({each:true})
    @Type(()=>ProjectLocation)
    location:ProjectLocation
}

but when another nested layer is added to ProjectLocation it doesn't work and also you can't use @ValidatedNested inside ProjectLocation to add another class Type to it .

Error : No overload matches this call.

Upvotes: 1

Views: 2324

Answers (1)

eol
eol

Reputation: 24565

Works as expected for me, consider the following:

class SomeNestedObject {
    @IsString()
    someProp: string;
}

class ProjectLocation {
    @IsString()
    longitude: string;
    @IsString()
    latitude: string;
    @ValidateNested()
    @IsNotEmpty()
    @Type(() => SomeNestedObject)
    someNestedObject: SomeNestedObject;
}

export class CreateProjectDto {
    @IsString()
    address: string;
    @ValidateNested()
    @Type(() => ProjectLocation)
    location: ProjectLocation;
}

Note that I'm using IsNotEmpty on someNestedObject to handle the case if the prop is missing.


Here's two examples of invalid requests that are validated correctly:

Example 1:

Request-Body:    
    {
        "address": "abc",
        "location": { 
            "longitude": "123",
            "latitude" : "456",
            "someNestedObject": {}
        }
    }

Response:
{
    "statusCode": 400,
    "message": [
        "location.someNestedObject.someProp should not be empty"
    ],
    "error": "Bad Request"
}

Example 2:

Request-Body:
{
    "address": "abc",
    "location": { 
        "longitude": "123",
        "latitude" : "456"
    }
}
Response:
{
    "statusCode": 400,
    "message": [
        "location.someNestedObject should not be empty"
    ],
    "error": "Bad Request"
}

Upvotes: 1

Related Questions