如何使用有条件的 Joi 替代方案进行模式验证?
How to use Joi alternatives conditional for schema validation?
我有一个用例,其中架构字段是必需的,具体取决于另一个字段的值,
例如。如果模式有 2 个字段,name 和 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 有错误消息,指出地址字段丢失。
我试着参考 -
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() })
})
我有一个用例,其中架构字段是必需的,具体取决于另一个字段的值,
例如。如果模式有 2 个字段,name 和 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 有错误消息,指出地址字段丢失。
我试着参考 -
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() })
})