簡體   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