繁体   English   中英

Joi 验证器条件模式

[英]Joi validator conditional schema

我需要创建动态模式以根据请求查询中的键使用Joi 验证器node js验证我的 api 请求查询。 说下面提到的模式是我的有效查询。

我正在使用hapi/joi 16.1.8版本16.1.8

组合1

{ type: 1, firstname: 'user first name', lastname: 'user last name'}

组合2

{ type: 2 , salary: 1000, pension: 200}

组合3

{ type: 3 , credit: 550, debit: 100}

如您所见,对象键因type的值而异。 如何正确处理?

我们可以使用Joi.alternatives处理两个条件,例如

const schema = Joi.alternatives().conditional(Joi.object({ type: 1 }).unknown(), {
    then: Joi.object({
        type: Joi.string(),
        firstname: Joi.string(),
        lastname: Joi.string()
    }),
    otherwise: Joi.object({
        type: Joi.number(),
        salary: Joi.any(),
        pension: Joi.any()
    })
});

但是如何在 3 个条件下做到这一点?

我以稍微不同的方式实现了相同的目标。 在这里发布相同的内容,因为这可能对将来的某人有用。

const schema = Joi.object({
    type: Joi.number().required().valid(1, 2, 3),
    firstname: Joi.alternatives().conditional('type', { is: 1, then: Joi.string().required() }),
    lastname: Joi.alternatives().conditional('type', { is: 1, then: Joi.string().required() }),
    salary: Joi.alternatives().conditional('type', { is: 2, then: Joi.number().required() }),
    pension: Joi.alternatives().conditional('type', { is: 2, then: Joi.number().required() }),
    credit: Joi.alternatives().conditional('type', { is: 3, then: Joi.number().required() }),
    debit: Joi.alternatives().conditional('type', { is: 3, then: Joi.number().required() }),
}))

这正如预期的那样完美地工作。

当类型值为1 ,对象应该只有typefirstnamelastname

当类型值为2 ,对象应该只有typesalarypension

当 type 值为3 ,对象应该只有typecreditdebit

任何其他组合都将从 joi 验证器中间件层作为错误抛出。 此外,除 1、2 和 3 之外的任何其他类型值都将引发错误。

这个对我有用!

var Joi = require('joi');

var schema = {
    a: Joi.any().when('b', { is: 5, then: Joi.required(), otherwise: Joi.optional() }),
    b: Joi.any()
};

var thing = {
    b: 5
};
var validate = Joi.validate(thing, schema);

// returns
{
    error: null,
    value: {
        b: 5
    }
}

这是 参考

文档中,看起来switch是与alternatives.conditional一起使用的有效键。 您可以尝试以下方法吗?

const schema = Joi.alternatives().conditional(Joi.object({
  type: 1
}).unknown(), {
  switch: [{
    is: 1,

    then: Joi.object({
      type: Joi.string(),
      firstname: Joi.string(),
      lastname: Joi.string(),
    }),
  }, {
    is: 2,

    then: Joi.object({
      type: Joi.number(),
      salary: Joi.any(),
      pension: Joi.any(),
    }),
  }, {
    // ...
  }],
});

编辑

在任何地方都找不到有关使用switch关键字的任何示例...

但是在hapijs/joi github 中找到了一些其他方法来实现它

const schema = Joi.object({
     a: Joi.number().required(),
     b: Joi.alternatives()
             .conditional('a', [
                 { is: 0, then: Joi.valid(1) },
                 { is: 1, then: Joi.valid(2) },
                 { is: 2, then: Joi.valid(3), otherwise: Joi.valid(4) }
    ])
});

我试图找到一种方法来做类似的事情。 然后我就想通了。

const Joi = require('joi');
const schema = Joi.object({
  type: Joi.number().valid(1,2,3),
  // anything common
}).when(Joi.object({type: Joi.number().valid(1)}).unknown(), {
  then: Joi.object({
    firstname: Joi.string(),
    lastname: Joi.string(),
  })
})
.when(Joi.object({type: Joi.number().valid(2)}).unknown(), {
  then: Joi.object({
    salary: Joi.number(),
    pension: Joi.number(),
  })
})
.when(Joi.object({type: Joi.number().valid(3)}).unknown(), {
  then: Joi.object({
    credit: Joi.number(),
    debit: Joi.number(),
  })
});

我想做同样的事情,但条件应该取决于请求方法而不是查询参数。 我最终得到了下一个解决方案:

const schema = Joi.when(Joi.ref("$requestMethod"), {
  switch: [
    {
      is: "POST",
      then: Joi.object({
        name: Joi.string().trim().max(150).required(),
        description: Joi.string().max(255),
        active: Joi.boolean().required(),
        }),
      }),
    },
    {
      is: "PUT",
      then: Joi.object({
        name: Joi.string().trim().max(150).required(),
        description: Joi.string().max(255),            
      }),
    },
  ],
});


schema.validate(req.body, { context: { requestMethod: req.method } });

Joi when() 条件文档https://joi.dev/api/?v=17.4.1#anywhencondition-options

使用条件/开关,其语法也更具可读性。

以下 Joi 摘录将在$.type === Type.REFERENCE时强制$.referenceClass的存在。 当它这样做时,它将确保值是接受的值 - ...classIds

否则( $.type !== Type.REFERENCE ),它将不允许$.referenceClass的存在(除非您使用允许额外键的选项运行验证)。

{
    type: Joi.string().valid( ...Hub.types ).required(),
    referenceClass: Joi.alternatives().conditional( 'type', {
        switch: [
            { is: Type.REFERENCE, then: Joi.string().valid( ...classIds ) },
        ],
    } ),
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM