1

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.

1 Answer 1

1

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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you works for me as well. seems like we should explicitly ask it to validate something on nested object key to make it validate inner types .
this does not work in case of arrays how do we handle that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.