2

我有一个示例类(https://github.com/typestack/class-validator#validation-messages)。我创建了一个应该执行正常验证的函数,或者,如果指定,如果title字段包含在正在验证的实例中,则执行失败的验证。

import {MinLength, MaxLength, validate} from "class-validator";

export class Post {

    @IsString()
    body: strong;

    @IsString()
    title: string;

    public async validatePost(isTitle){
        // if we want the title to be included in the instance, do normal validation
        if(isTitle) {
            validate(this, { forbidUnknownValues: true, validationError: { target: false } });
        }
        // if a title is provided, fail validation
        else {
            // TODO: How can I fail validation if `title` is part of the instance?
        }
    }

}

我知道当存在未列入白名单的属性时(https://github.com/typestack/class-validator#whitelisting)可能会引发错误,但我似乎无法弄清楚如何有条件地失败验证如果一个字段存在。如果不创建自定义装饰器,这甚至可能吗?

4

1 回答 1

1

有几种选择:

你可以添加一个条件:https ://github.com/typestack/class-validator#conditional-validation

@ValidateIf(o => o.otherProperty === "value")
@Equals(undefined)
title: string;

如果您希望它始终未定义:

@Equals(undefined)
title: string;

如果使用class-transformer,则可以将其标记@Excluded为发送的任何值都不会设置为该字段。

@Exclude({ toPClassOnly: true })
title: string;
于 2020-04-21T07:42:07.670 回答