Sin*_*ner 10 validation typescript 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
Run Code Online (Sandbox Code Playgroud)
我尝试将变量输入到 @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;
}
Run Code Online (Sandbox Code Playgroud)
我收到TS7017 错误。
TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
Run Code Online (Sandbox Code Playgroud)
有没有什么完美的方法来处理这个问题?
我知道有像下面这样的简单方法,但我希望有某种方法可以使用类验证器。
TS7017: Element implicitly has an 'any' type because type 'typeof globalThis' has no index signature.
Run Code Online (Sandbox Code Playgroud)
小智 15
是的,您可以,但不是本机的,在这种情况下您需要创建自己的装饰器来实现此验证。这是一个例子:
首先创建你的装饰器验证器
// 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;
},
},
});
};
}
Run Code Online (Sandbox Code Playgroud)
然后将其导入到您的 dto 中
import { IsBiggerThan } from '../../validators/is-bigger-than';
export class SomeObjectDTO {
minValue: number;
@IsBiggerThan('minValue', {
message: 'maxValue must be larger than minValue',
})
maxValue: number;
}
Run Code Online (Sandbox Code Playgroud)
经过测试并有效(请参阅单元测试来源):
归档时间: |
|
查看次数: |
13778 次 |
最近记录: |