Nest JS Class Validator Array of Integers

89 Views Asked by At

I am trying validate that a parameter being sent in nest js is an array of integers. The below works if I get rid of @IsInt({ each: true }), however it allows for decimals as well.

I've tried type: Int32Array and that does not work either.

export class SearchRequest {
  @IsArray()
  @IsInt({ each: true })
  @ApiProperty({
    description: 'The ids used to perform the search.',
    type: [Number],
    example: [13245, 54321],
  })
  ids: number[];
}

Using the above code, I get this error in swagger despite passing in integers:

{
  "message": [
    "each value in ids must be an integer number"
  ],
  "error": "Bad Request",
  "statusCode": 400
}
1

There are 1 best solutions below

4
On

You should get rid of @IsArray() instead of @IsInt({ each: true }) because the each flag indicates that ids is an array and every element has to be an integer:

export interface ValidationOptions {
    /**
     * Specifies if validated value is an array and each of its items must be validated.
     */
    each?: boolean;

So this code should work:

export class SearchRequest {
  @IsInt({ each: true })
  @ApiProperty({
    description: 'The ids used to perform the search.',
    type: [Number],
    example: [13245, 54321],
  })
  ids: number[];
}