簡體   English   中英

如何為 TypeScript 類執行 Joi 驗證?

[英]How to perform Joi Validations for a TypeScript Class?

我能夠對節點中的函數表達式執行 Joi 驗證,如下所示

export var shippingInfo = Joi.object().keys({
   expectedDeliveryDate:Joi.date().required(),
   isRegisteredCompanyAddress:Joi.number().required(),
   addressLine:Joi.string(),
   country:Joi.string(),
   state:Joi.string(),
   city:Joi.string(),
   zipcode:Joi.string()
});

但問題是,我最近開始研究打字稿。 所以在這里,我有幾個類,我應該像在上面的函數表達式中那樣執行 Joi 驗證。 即我想驗證下面的類

export class ShippingInfo {
   expectedDeliveryDate: Date,
   isRegisteredCompanyAddress: number,
   addressLine:string,
   country:string,
   state:string,
   city:string,
   zipcode:string
}

我應該如何對上述課程進行驗證。 應該對類級別還是對象級別進行驗證? 如何?

您可以將此項目用作參考。 tsdv-joi

// ...imports...

registerJoi(Joi);

class MyClass {
    @Max(5)
    @Min(2)
    @StringSchema
    public myProperty : string;
}

let instance = new MyClass();
instance.myProperty = "a";

const validator = new Validator();
var result = validator.validate(instance);
console.log(result); // outputs the Joi returned value

如果你需要 npm 包,那么你可以使用這個包裝器gearworks

您可以使用class-from-anytsdv-joiclass-validatorclass-transformer

來自任何類的示例,我們在其中獲取、轉換和驗證 JSON 數據作為打字稿類:

import { FromAny, GetFrom, Validate, isString, notEmpty } from "class-from-any";

const worldJSONData = `{"name": "Earth"}`;

class World extends FromAny {
    @GetFrom("name") @Validate(isString, notEmpty) title: string;
}

const world = new World().from(
    JSON.parse(worldJSONData) as Record<string, unknown>
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM