使用 Joi 的 when
方法来按条件验证两个模式。
示例代码:
const Joi = require('joi');
// 定义两个模式,用于验证不同情况下的数据
const schema1 = Joi.object({
name: Joi.string().required(),
age: Joi.number().min(18),
});
const schema2 = Joi.object({
name: Joi.string().required(),
email: Joi.string().email().required(),
});
// 定义用于判断需要验证哪个模式的方法
const isConditionMet = (data) => {
// 判断数据中是否有 email 字段
return data.email !== undefined;
};
// 根据条件选择需要验证的模式
const schemaToUse = Joi.when(Joi.object({}), {
then: Joi.when(Joi.object({
email: Joi.any().required(),
}), {
then: schema2,
otherwise: schema1,
}),
});
// 测试数据
const data1 = { name: 'John', age: 25 };
const data2 = { name: 'Mary', email: 'mary@example.com' };
// 验证数据
const result1 = schemaToUse.validate(data1);
const result2 = schemaToUse.validate(data2);
console.log(result1); // 通过,返回 { value: { name: 'John', age: 25 } }
console.log(result2); // 通过,返回 { value: { name: 'Mary', email: 'mary@example.com' } }
在上面的示例中,我们定义了两个模式 schema1
和 schema2
,用于验证不同情况下的数据。然后,我们使用 Joi.when
方法来根据条件选择需要验证的模式。具体来说,我们通过定义一个 isConditionMet
方法来判断数据中是否有 email 字段,如果有,则使用 schema2
来验证数据,否则使用 schema1
。最后,我们可以使用 schemaToUse
来验证数据,无论数据中是否有 email 字段,都可以得到正确的
上一篇:按条件选择列
下一篇:按条件依次执行可观察数组