簡體   English   中英

Joi中可選條件的模式

[英]Schema for optional conditions in Joi

假設我有一個像這樣的對象:

{
  a : 1,
  b : 2,
  c : 3,
  d : 4
}

[a,b], [a,c], [d] 至少一對應該通過驗證(具有正確的值)。

假設所有值都是數字

如何為它創建Joi架構。

您可以使用Joi.alternatives()並創建一個這樣的Joi架構:

Joi.alternatives().try(
    Joi.object({
        a: Joi.number().required(),
        b: Joi.number().required(),
        c: Joi.number(),
        d: Joi.number()
    }),
    Joi.object({
        a: Joi.number().required(),
        b: Joi.number(),
        c: Joi.number().required(),
        d: Joi.number()
    }),
    Joi.object({
        a: Joi.number(),
        b: Joi.number(),
        c: Joi.number(),
        d: Joi.number().required()
    }),
)

還有另一種替代方法使用.requiredKeys ()並簡化上面的代碼:

const JoiObjectKeys = {
    a: Joi.number(),
    b: Joi.number(),
    c: Joi.number(),
    d: Joi.number()
}

Joi.alternatives().try(
    Joi.object(JoiObjectKeys).requiredKeys('a', 'b'),
    Joi.object(JoiObjectKeys).requiredKeys('a', 'c'),
    Joi.object(JoiObjectKeys).requiredKeys('d'),
);

使用此架構,您將獲得以下結果:

{ a: 1 } > fails
{ b: 1 } > fails
{ c: 1 } > fails
{ a: 1, b: 1 } > passes
{ a: 1: c: 1 } > passes
{ d: 1 } > passes
{ d: 1, a: 1 } > passes

小心使用Joi.number() 它也會認為'3'是有效的 - 如果你使用的是Joi.assert它實際上並沒有把它變成3 Joi.assert 為避免這種情況,您應該添加.strict()修飾符。

請參閱https://medium.com/east-pole/surprised-by-joi-35a3558eda30

暫無
暫無

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

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