在使用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