Nestjs + Class-validator: Validating decimal values

143 views Asked by At

I just ran into a pretty simple issue, this definition normally should have worked perfectly and pass the validation as price field in JSON is already sent in decimal format as you can figure below, but class-validator keeps raising such error even though I meet the criterias.Whats the best practices to handling this kind of validations on Nestjs, wondering how everyone else would handle that, thanks

create-product.dto.ts

  @IsDecimal({ force_decimal: true, decimal_digits: '2' })
  @IsNotEmpty({ message: 'Price is required' })
  @Min(0, { message: 'Price must be greater than or equal to 0' })
  price: number;

request sent

{
 // other fields...

    "price" : 1574.23,

}

response

{
    "message": [
        "price is not a valid decimal number."
    ],
    "error": "Bad Request",
    "statusCode": 400
}

tried to switch to @IsNumberString type as well but got no luck

1

There are 1 answers

0
user23646024 On

@IsDecimal can only be used with type string and not with type number. So I guess you have transformation enabled in the main.ts file.

In any case, you should be able to use:

@IsNumber({maxDecimalPlaces: 2})