可以使用自定义验证器:
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