【问题标题】:validating multi-layers nested objects in nestjs在nestjs中验证多层嵌套对象
【发布时间】:2021-05-05 18:48:14
【问题描述】:

我正在尝试在 nestJs 中使用 classValidator 装饰器来验证以下类型的传入请求

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

。问题是它仅限于一层 nestedObject 。下面的一个工作

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

export class CreateProjectDto {

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

但是当另一个嵌套层添加到 ProjectLocation 时,它不起作用,而且您不能在 ProjectLocation 中使用 @ValidatedNested 向其中添加另一个类类型。

错误:没有重载匹配此调用。

【问题讨论】:

    标签: javascript node.js nestjs class-validator


    【解决方案1】:

    按预期工作,请考虑以下几点:

    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;
    }
    

    请注意,如果缺少道具,我将在 someNestedObject 上使用 IsNotEmpty 来处理这种情况。


    以下是两个正确验证的无效请求示例:

    示例 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"
    }
    

    示例 2:

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

    【讨论】:

    • 谢谢你也为我工作。似乎我们应该明确要求它验证嵌套对象键上的某些内容以使其验证内部类型。
    • 这在数组的情况下不起作用我们如何处理它
    猜你喜欢
    • 2021-04-22
    • 2019-05-16
    • 2020-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-21
    • 2021-07-11
    • 2011-03-21
    相关资源
    最近更新 更多