【问题标题】:Validation for array objects using class-validator in node js在节点 js 中使用类验证器验证数组对象
【发布时间】:2020-04-02 11:21:32
【问题描述】:

如果它是空的,我想验证酒精 ID 和酒精名称。这是我的格式:

   {
     "barId": "string",
     "barName": "string",
     "drinksItems": [
      {
      "alcoholId": "string",
      "alcoholName": "string",
      "mixerList": [
         {
           "mixerId": "string"
         }
       ],
      "modifierList": [
         {
           "modifierId": "string"
         }
       ]
    }]
}

【问题讨论】:

    标签: node.js typescript class-validator


    【解决方案1】:

    为此,您需要有一个实体并使用@ValidateNested@Type 正确转换它(仅在您使用class-transformer 的情况下)。

    class Alcohol {
        @IsNotEmpty()
        alcoholId: string;
        @IsNotEmpty()
        alcoholName: string;
    }
    
    class Bar {
        @IsNotEmpty() // <- requires the array to be present
        @ValidateNested()
        // @Type(() => Alcohol) // <- add only if you use class-transformer
        alcohols: Array<Alcohol>;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-03-09
      • 2018-08-21
      • 2020-07-30
      • 2022-01-10
      • 2022-12-11
      • 1970-01-01
      • 2021-04-22
      • 2021-05-19
      • 1970-01-01
      相关资源
      最近更新 更多