How to solve the problem of query parameters validation in class validator

69 Views Asked by At

I use class-validator to validate query parameters in nest js,why validator does not understand such a syntax as a key ?

     class Example {
        @IsOptional()
        @IsObject()
        price[$gte]': { $gte: number };
     }

Request in insomnia

Is there any way to solve this problem ?

1

There are 1 best solutions below

0
Maxim Baykalov On

To make the behaviour working you could use code like this:

import { Controller, Get, Query } from '@nestjs/common';
import { IsNumber, IsObject,ValidateNested } from 'class-validator';
import { Transform, Type } from 'class-transformer';

export class PriceFilter {
  @Transform(({ value }) => +value)
  @IsNumber()
  gte: boolean;
}

export class MyFilterQuery {
  @ValidateNested()
  @Type(() => PriceFilter)
  @IsObject()
  price: PriceFilter;
}

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get()
  getHello(@Query() query: MyFilterQuery): string {
    console.log(query);
    return this.appService.getHello();
  }
}

Please, make sure that you have the following section inside bootstrap() function in your main.ts file in src folder

app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
    }),
);