我可以将数字变量与 'class-validator' 进行比较吗?

Can I compare number variables with 'class-validator'?

嗨!我有一个关于 class-validator

的问题

我的客户会要求多个号码,我需要相互比较数值。

我想要如下代码。

const validator: SomeValidator = new SomeValidator;
validator.first = 1000;
validator.second = 2000; // this will be greater than validator.first
validator.third = 3000; // this will be greater than validator.second

我尝试将变量输入到 @Min() 验证器中,如下所示

import { IsInt, Min } from 'class-validator';

class SomeValidator {

  @IsInt()
  @Min(0)
  public first: number;

  @IsInt()
  @Min(this.first) // it occurs TS7017
  public second: number;

  @IsInt()
  @Min(this.second) // it occurs TS7017
  public third: number;

}

我遇到了 TS7017 错误

TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.

有什么完美的方法可以解决这个问题吗?

我知道有如下简单的方法,但是我希望有一些方法可以使用 class-validator。

if ((first > second) || (second > third)) {
  res.status(400).json({
    message: 'validation failed',
  });
  return next(new Error('some error'));

是的,你可以,但不是原生的,在这种情况下你需要创建你自己的装饰器来实现这个验证。这是一个例子:

首先创建装饰器验证器

// file validators/is-bigger-than.ts
import { registerDecorator, ValidationOptions, ValidationArguments } from 'class-validator';

export function IsBiggerThan(property: string, validationOptions?: ValidationOptions) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'isBiggerThan',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        validate(value: any, args: ValidationArguments) {
          const [relatedPropertyName] = args.constraints;
          const relatedValue = (args.object as any)[relatedPropertyName];
          return typeof value === 'number' && typeof relatedValue === 'number' && value > relatedValue;
        },
      },
    });
  };
}

然后在你的dto中导入它

import { IsBiggerThan } from '../../validators/is-bigger-than';

export class SomeObjectDTO {
  minValue: number;


  @IsBiggerThan('minValue', {
    message: 'maxValue must be larger than minValue',
  })
  maxValue: number;
}