我有一个用@MinDate约束装饰的类,如下所示:
export default class Order {
purchaseDate: Date;
@MinDate(this.purchaseDate)
receiptDate: Date;
}
尝试验证有效验证错误的Order
实例时。我的问题是,将this.purchaseDate
作为参数传递给@MinDate()
装饰者甚至可能/有效。
换句话说,typescript decorators可以从一个对象接收运行时值,还是这些值必须在编译时可用?例如:
@MinDate(new Date(12/22/2017)); //This should work?
@MinDate(this.someDate) // This will never work?
答案 0 :(得分:2)
不,你做不到。
装饰器应用于类而不是实例,这意味着在调用装饰器函数时没有this
。
使用静态值将起作用:
@MinDate(new Date(12/22/2017));
但你不能使用实例成员。
你可以在没有装饰器的构造函数中做到这一点:
export default class Order {
...
constructor() {
this.purchaseDate = ...
this.receiptDate = this.purchaseDate;
}
}
答案 1 :(得分:2)
可以使用自定义验证程序:
import {registerDecorator, ValidationOptions, ValidationArguments} from "class-validator";
export function IsGreaterThan(property: string, validationOptions?: ValidationOptions) {
return function (object: Object, propertyName: string) {
registerDecorator({
name: "IsGreaterThan",
target: object.constructor,
propertyName: propertyName,
constraints: [property],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments) {
const [relatedPropertyName] = args.constraints;
const relatedValue = args.object[relatedPropertyName];
return value > relatedValue;
}
}
});
};
}
用法:
import { IsGreaterThan } from "./IsLongerThan";
export class Post {
purchaseDate: string;
@IsGreaterThan("purchaseDate", { message: "receiptDate must be greater than purchaseDate" })
text: string;
}
更多详细信息可以在文档中找到:https://github.com/typestack/class-validator#custom-validation-decorators