我有一個用例,其中架構欄位是強制性的,具體取決于另一個欄位的值,
例如。如果模式有 2 個欄位,name 和 addr,
如果 name 欄位的值為“test”,則 addr 欄位是必需的。
我正在使用 Joi 進行物件驗證,
以下是我的示例代碼 -
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();
電流輸出 -
validationResponse => { value: { name: 'test' } }
我期待的是validationResponse 有錯誤訊息,表明addr 欄位丟失。
我試著參考 -
https://www.npmjs.com/package/joi
https://joi.dev/api/?v=17.4.2#alternativesconditionalcondition-options
uj5u.com熱心網友回復:
你真的需要Joi.alternatives嗎?為什么不使用Joi.when呢?
Joi.object({
name: Joi.string().required(),
addr: Joi.string().when('name', { is: 'test', then: Joi.required() })
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/312689.html
標籤:javascript 节点.js 验证 乔伊
