【问题标题】:Validate class: Fail validation if field is present验证类:如果存在字段,则验证失败
【发布时间】:2020-08-03 11:17:36
【问题描述】:

我有一个示例类 (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) 时可能会引发错误,但我似乎无法弄清楚如何在存在字段时有条件地使验证失败。如果不创建自定义装饰器,这是否可能?

【问题讨论】:

    标签: typescript validation class-validator


    【解决方案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;
    

    【讨论】:

      猜你喜欢
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-23
      • 1970-01-01
      相关资源
      最近更新 更多