32

我正在使用带有 NestJS 的 class-validator 包,并且我希望验证一个对象数组,这些对象需要恰好有 2 个具有相同布局的对象:

到目前为止,我有:

import { IsString, IsNumber } from 'class-validator';

export class AuthParam {
  @IsNumber()
  id: number;

  @IsString()
  type: string;

  @IsString()
  value: string;
}

import { IsArray, ValidateNested } from 'class-validator';
import { AuthParam } from './authParam.model';

export class SignIn {
  @IsArray()
  @ValidateNested({ each: true })
  authParameters: AuthParam[];
}

根据@kamilg 的回复(我能够强制执行 2 个元素):

import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';
import { AuthParam } from './authParam.model';

export class SignInModel {
  @IsArray()
  @ValidateNested({ each: true })
  @ArrayMinSize(2)
  @ArrayMaxSize(2)
  authParameters: AuthParam[];
}

我仍然可以传递一个空数组或一个包含与 AuthParam 无关的其他对象的数组。

我应该如何修改它来获得验证?

另外,我如何在数组中强制执行 2 个元素?MinLength(2) 似乎与字符串有关...(已解决)

4

5 回答 5

89

添加@Type(() => AuthParam)到您的阵列,它应该工作。Type嵌套对象(数组)需要装饰器。你的代码变成

import { IsArray, ValidateNested, ArrayMinSize, ArrayMaxSize } from 'class-validator';
import { AuthParam } from './authParam.model';
import { Type } from 'class-transformer';

export class SignInModel {
  @IsArray()
  @ValidateNested({ each: true })
  @ArrayMinSize(2)
  @ArrayMaxSize(2)
  @Type(() => AuthParam)
  authParameters: AuthParam[];
}

如果您使用任何异常过滤器来修改错误响应,请小心。确保您了解类验证器错误的结构。

于 2019-10-13T18:04:46.993 回答
3

我知道我迟到了,但遇到了一些类型问题,然后尝试另一种实现方式:

export class AuthParam {
    @IsNumber()
    id: number;
  
    @IsString()
    type: string;
  
    @IsString()
    value: string;
  }

验证功能

@ValidatorConstraint()
export class IsAuthArray implements ValidatorConstraintInterface {
    public async validate(authData: AuthParam[], args: ValidationArguments) {
        return Array.isArray(authData) && authData.reduce((a, b) => a && (typeof b.id === "number") && typeof b.type === "string" && typeof b.field === "string", true);
    }
}

export class SignInModel {
    @IsNotEmpty()
    @IsArray()
    @ArrayMinSize(2)
    @ArrayMaxSize(2)
    @Validate(IsAuthArray, {
        message: "Enter valid value .",
    })
    authParameters: AuthParam[];
  }

也许它会帮助某人

于 2021-05-13T06:54:07.300 回答
3

您可以使用以下内容:

validator.arrayNotEmpty(array); // Checks if given array is not empty.

validator.arrayMinSize(array, min); // Checks if array's length is at least `min` number.

https://github.com/typestack/class-validator#manual-validation

您可能需要考虑编写自定义验证器,以更好地反映您的业务需求。

于 2019-10-11T16:25:57.993 回答
1

const param1: AuthParam = Object.assign(new AuthParam(), {
  id: 1,
  type: 'grant',
  value: 'password'
})

const param2: AuthParam = Object.assign(new AuthParam(), {
  id: 1,
  type: 4,
  value: 'password'
})

const signInTest = new SignInModel()
signInTest.authParameters = [param1, param2]

validate(signInTest).then(e => {
  console.log(e[0].children[0].children[0])
})

这工作正常,这是:

ValidationError {
  target: AuthParam { id: 1, type: 4, value: 'password' },
  value: 4,
  property: 'type',
  children: [],
  constraints: { isString: 'type must be a string' } }

所以我只能假设正在验证的对象不是AuthParam

const param2: AuthParam = {
  id: 1,
  type: 4,
  value: 'password'
} as any

正如预期的那样,这个对象上没有任何装饰器(这可能适用于 Nest.js 控制器和来自 body/req 的嵌套对象) - 因此忽略验证。

请检查这个(tl;dr -@Type装饰者表格class-transformer

于 2019-10-11T20:39:26.253 回答
-1

https://github.com/typestack/class-validator/pull/295

刚刚发表在v0.10.2,所以它应该有所帮助,希望!

于 2019-10-14T12:58:16.497 回答