gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:16:25 25 4
gpt4 key购买 nike

你好!我有一个关于类验证器的问题

我的客户将请求多个数字,我需要相互比较值。

我想要像下面这样的代码。

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.

有没有完美的方法来处理这个问题?

我知道有像下面这样的简单方法,但是 我希望有一些方法可以使用类验证器。

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

最佳答案

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

// 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;
}

关于typescript - 我可以将数字变量与 'class-validator' 进行比较吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59980341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com