我刚刚遇到了一个非常简单的问题,这个定义通常应该完美地工作并通过验证,因为 JSON 中的价格字段已经以十进制格式发送,如下图所示,但类验证器不断引发此类错误,即使我遇到标准。在 Nestjs 上处理此类验证的最佳实践是什么,想知道其他人会如何处理,谢谢
创建产品.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;
请求已发送
{
// other fields...
"price" : 1574.23,
}
回应
{
"message": [
"price is not a valid decimal number."
],
"error": "Bad Request",
"statusCode": 400
}
也尝试切换到@IsNumberString类型,但没有成功
@IsDecimal 只能与字符串类型一起使用,不能与数字类型一起使用。所以我猜你在 main.ts 文件中启用了转换。
无论如何,您应该能够使用:
@IsNumber({maxDecimalPlaces: 2})