Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
NestJS创建一个自定义长度验证器,其工作方式类似于IsIn,允许的长度在数组中传递_Nestjs_Class Validator - Fatal编程技术网

NestJS创建一个自定义长度验证器,其工作方式类似于IsIn,允许的长度在数组中传递

NestJS创建一个自定义长度验证器,其工作方式类似于IsIn,允许的长度在数组中传递,nestjs,class-validator,Nestjs,Class Validator,我想构建一个自定义验证器,它的工作方式类似于,接受一个值数组,它是可以使用的字段长度。我希望能够通过允许长度的数组进行检查。虽然我已经研究了类验证器上的IsIn代码,但我不确定如何将其转换为NestJS 我试图验证长度可能为12或32位的数据(旧系统、新系统),但不验证其他长度的数据,因此当前的@length()是不够的 我需要能够创建一个@LengthIn()样式的验证器,在这里我可以使用decorator中的大小 @IsString@LengthIn([12,32])公共只读包成员:stri

我想构建一个自定义验证器,它的工作方式类似于,接受一个值数组,它是可以使用的字段长度。我希望能够通过允许长度的数组进行检查。虽然我已经研究了类验证器上的IsIn代码,但我不确定如何将其转换为NestJS

我试图验证长度可能为12或32位的数据(旧系统、新系统),但不验证其他长度的数据,因此当前的@length()是不够的

我需要能够创建一个@LengthIn()样式的验证器,在这里我可以使用decorator中的大小

@IsString@LengthIn([12,32])公共只读包成员:string

我希望在DTO类中使用它进行标准验证

我不知道如何将@IsIn调用转换为NestJS装饰程序。这是我尝试过的,但不起作用

import { registerDecorator, ValidationArguments, ValidationOptions, ValidatorConstraint, ValidatorConstraintInterface } from 'class-validator';

export function LengthIn(property: string, validationOptions?: ValidationOptions) {
    return function (object: Object, propertyName: string) {
        registerDecorator({
            target: object.constructor,
            propertyName: propertyName,
            options: validationOptions,
            constraints: [property],
            validator: IsLongerThanConstraint,
        });
    };
}

@ValidatorConstraint({ name: 'LengthIn' })
export class IsLongerThanConstraint implements ValidatorConstraintInterface {
    validate(value: any, args: ValidationArguments) {
        const AllowedLengths:number[] = args.constraints;       // How to I set an array of values?
        let LengthIsGood:boolean = false;
        AllowedLengths.forEach( (Length:number) => {
            if (value.length === Length) {
                LengthIsGood = true;
            }
        });
        return typeof value === 'string' && LengthIsGood;
    }
}
问题是我不知道如何将处理接受传递的正确值数组的代码添加到Validator约束中