繁体   English   中英

如何使用有条件的 Joi 替代方案进行模式验证?

[英]How to use Joi alternatives conditional for schema validation?

我有一个用例,其中模式字段是强制性的,具体取决于另一个字段的值,
例如。 如果模式有 2 个字段,name 和 addr,
如果 name 字段的值为“test”,则 addr 字段是必需的。

我正在使用 Joi 进行 object 验证,
以下是我的示例代码 -

const Joi = require('joi');


let test = async() => {
    const schema = Joi.object({
        name: Joi.string().required(),
        addr: Joi.alternatives().conditional('name', {is: 'test', then: Joi.string().required()})
    });

    const request = {
        name: "test"
    }

    // schema options
    const options = {
        abortEarly: false, // include all errors
        allowUnknown: true, // ignore unknown props
        stripUnknown: true // remove unknown props
    };

    // validate request body against schema
    const validationResponse = await schema.validate(request, options);
    console.log("validationResponse => ", validationResponse);

    return true;
};

test();

当前 output - validationResponse => { value: { name: 'test' } }

我期望的是 validationResponse 有错误消息,指出地址字段丢失。

我试着提到 -
https://www.npmjs.com/package/joi
https://joi.dev/api/?v=17.4.2#alternativesconditionalcondition-options

你真的需要Joi.alternatives吗? 你为什么不使用Joi.when呢?

 Joi.object({
   name: Joi.string().required(),
   addr: Joi.string().when('name', { is: 'test', then: Joi.required() })
 })

暂无
暂无

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

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