4

我有一个用@MinDate 约束装饰的类,如下所示:

export default class Order {
   purchaseDate: Date;
   @MinDate(this.purchaseDate)
   receiptDate: Date;
}

当试图验证一个Order有效的实例时,验证错误就会出现。我的问题是this.purchaseDate作为参数传递给@MinDate()装饰器是否有可能/有效。

换句话说,打字稿装饰器可以从对象接收运行时值,还是这些值必须在编译时可用?例如:

@MinDate(new Date(12/22/2017));  //This should work?
@MinDate(this.someDate) // This will never work?
4

2 回答 2

4

不,你不能那样做。
装饰器应用于类而不是实例,这意味着this调用装饰器函数时没有。

使用静态值将起作用:

@MinDate(new Date(12/22/2017));

但是您不能为其使用实例成员。

您可以在没有装饰器的构造函数中执行此操作:

export default class Order {
    ...
    constructor() {
        this.purchaseDate = ...
        this.receiptDate = this.purchaseDate;
    }
}
于 2017-05-02T16:34:45.670 回答
4

可以使用自定义验证器:

    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

于 2020-03-27T15:49:52.777 回答