简体   繁体   English

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

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

I have a use case where a schema field is mandatory depending on the value of another field,我有一个用例,其中模式字段是强制性的,具体取决于另一个字段的值,
eg.例如。 If the schema has 2 fields, name and addr,如果模式有 2 个字段,name 和 addr,
if the value of name field is "test" only then addr field is required.如果 name 字段的值为“test”,则 addr 字段是必需的。

I am using Joi for object validation,我正在使用 Joi 进行 object 验证,
Following is my sample code -以下是我的示例代码 -

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();

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

what I'm expecting is validationResponse to have error message that addr field is missing.我期望的是 validationResponse 有错误消息,指出地址字段丢失。

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

Do you really need Joi.alternatives ?你真的需要Joi.alternatives吗? Why don't you use Joi.when instead?你为什么不使用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