class-validator 复杂类型校验


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

 

    

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。