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