Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numeric parameter validation fails although requirements should pass [duplicate]

I want to fetch a location by coordinates. I started with a simple DTO

export class GetLocationByCoordinatesDTO {
    @IsNumber()
    @Min(-90)
    @Max(90)
    public latitude: number;

    @IsNumber()
    @Min(-180)
    @Max(180)
    public longitude: number;
}

and this API endpoint

@Get(':latitude/:longitude')
public getLocationByCoordinates(@Param() { latitude, longitude }: GetLocationByCoordinatesDTO): Promise<Location> {
  // ...
}

To test this endpoint I'm calling this url

localhost:3000/locations/0/0

and unfortunately I get the following response

{
    "statusCode": 400,
    "message": [
        "latitude must not be greater than 90",
        "latitude must not be less than -90",
        "latitude must be a number conforming to the specified constraints",
        "longitude must not be greater than 180",
        "longitude must not be less than -180",
        "longitude must be a number conforming to the specified constraints"
    ],
    "error": "Bad Request"
}

Does someone know how to fix this? I would expect it to pass.

It seems that the url params are considered strings but how can I parse them to numbers then?

like image 936
Question3r Avatar asked Oct 11 '25 08:10

Question3r


1 Answers

This is well known issue, more you can find on github issue.

Solution to your issue would be to explicitly cast the Number type in DTO like this:

import { Min, Max, IsNumber } from 'class-validator';
import { Type } from 'class-transformer';

export class GetLocationByCoordinatesDTO {
  @IsNumber()
  @Type(() => Number)
  @Min(-90)
  @Max(90)
  public latitude: number;

  @IsNumber()
  @Type(() => Number)
  @Min(-180)
  @Max(180)
  public longitude: number;
}

You need to install class-transformer in if you want this to work:

npm i class-transformer -S

Everything else should be fine.

like image 117
Ivan Vasiljevic Avatar answered Oct 15 '25 08:10

Ivan Vasiljevic