在使用class-validator进行参数校验的时候,会遇到[object,object]或[key:object]的情况!刚接触class-validator的小伙伴,遇到这种问题会比较头大(我刚遇到的这种情况也是很头大😂😂!)!废话不多少说,我们直接上代码:
1、数组中嵌套对象型-[object,object,...]
例如:[{self_warehouse_product_size_id: '1',stock: 2,price: 12.00 },....]
校验代码如下:
/* *数据模型 * [{self_warehouse_product_size_id: '1',stock: 2,price: 12.00 },....] */ class SizeList { @V.IsNumberString() self_warehouse_product_size_id: id_t @V.IsInt() @V.Min(1) stock: integer_t @V.IsDecimal() price: decimal_t } // 写法如下: @V.IsArray() @V.ArrayNotEmpty() @V.ValidateNested() @V.Type(() => SizeList) warehouseData: SizeList[]
2、对象嵌套对象型--{key:object}
例如:{merchant_synchronize_price_rule_id?: '1',rate: 2,difference_amount: 12.00,is_inclusive_lowest_threshold_amount: true, lowest_threshold_amount: 14.23, status: 'qy' }
代码如下:
class SynchronizePriceRule { @V.IsOptional() @V.IsNumberString() merchant_synchronize_price_rule_id: id_t @V.IsNumber() rate: float_t @V.IsDecimal() difference_amount: decimal_t @V.IsBoolean() is_inclusive_lowest_threshold_amount: boolean_t @V.IsDecimal() lowest_threshold_amount: decimal_t @V.IsEnum($ESynchronizePriceRuleStatus) status: $ESynchronizePriceRuleStatus } // 写法如下: @V.IsOptional() @V.ValidateNested() @V.Type(() => SynchronizePriceRule) synchronize_price_rule: SynchronizePriceRule