【发布时间】: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