类验证器忽略ValidateNested对象

时间:2020-06-01 13:52:36

标签: typescript class-validator

我在嵌套对象验证方面遇到问题。这是我的代码,它完全忽略了对嵌套对象的验证,我无法弄清原因:

import { IsNumber, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import "reflect-metadata";

export class SubClass {

    @IsNumber()
    public x : number;

    @IsNumber()
    public y : number;

    constructor( x : number, y : number){
        this.x = x;
        this.y = y; 
    };
};

export class Class {

    @IsArray()
    @ValidateNested({always: true, each: true})
    @Type(()=> SubClass)
    public nested ?: SubClass[];

    constructor(data : SubClass[]) {
        this.nested = data;
    }
}

一切都过去了,空的对象,错误的类型等。Plase帮助我以某种方式解决它。

示例: 测试: { x:'asd123', y:“ aasdf123” }通过。

1 个答案:

答案 0 :(得分:0)

对于任何其他遇到这种问题的人,我都想出了解决方案。如文档所述,validated属性必须是Class实例,以便验证装饰器可以工作。因此,这种情况的解决方案是:

import { IsNumber, ValidateNested } from 'class-validator';
import { Type } from 'class-transformer';
import "reflect-metadata";

export class SubClass {

    @IsNumber()
    public x : number;

    @IsNumber()
    public y : number;

    constructor( x : number, y : number){
        this.x = x;
        this.y = y; 
    }
}

export class Class {

    @IsArray()
    @ValidateNested({always: true, each: true})
    @Type(()=> SubClass)
    public nested ?: SubClass[];

    constructor(data : SubClass[]) {
        this.nested = data.map((data : SubClass) => new SubClass(data));
    }
}