如果value 需要string 或object(形状为{en: "value", es : "value"}),您可以使用
Joi.alternatives().try()
完整的代码如下所示..
const joiSchema = Joi.alternatives().try(Joi.string(),
Joi.object({
en: Joi.string()
.required(),
es: Joi.string()
.required(),
}))
const input1 = "Hello";
const input2 = {en: "Hi", es: "Hola"};
const joiResponse1 = joiSchema.validate(input1);
const joiResponse2 = joiSchema.validate(input2);
console.log(joiResponse1);
console.log(joiResponse2);
如果值是具有已知键的对象,例如“en”和“es”以及值必须是字符串的未知键,则可以使用Joi.pattern()。
const joiSchema = Joi.object({
en: Joi.string()
.required(),
es: Joi.string()
.required(),
}).pattern(Joi.string(), Joi.string())
const input = {en: "Hi", es: "Hola", ab: true};
const joiResponse = joiSchema.validate(input);
console.log(joiResponse);
这是一个同步调用。 joiSchema.validate 的返回值是一个具有以下结构的对象。
{ error: undefined or validation errors if any,
value: input value passed,
then: [Function: then],
catch: [Function: catch]
}
您可以检查joiResponse.error 的真假,看看是否有任何验证错误。
我在 Yup 中没有看到类似的功能(可能是我错了,因为我只是浏览了文档页面)。在我看来,我们能做的最好的事情就是使用Yup.lazy()创建一个基于对象的动态模式
let yupSchema = yup.lazy(obj => {
return yup.object(
{
...Object.keys(obj).reduce((acc, key) => {
acc[key] = yup.string().required()
return acc;
}, {}),
en: yup.string().required(),
es: yup.string().required()
}
);
});
//This should fail
const input3 = { en: "12", es: "Hola", fr: 1.1 };
yupSchema.validate(input3, {strict: true});
正如你所说,这会返回一个承诺。所以你应该使用返回的promise的then和catch子句来处理成功和失败。
但也有同步版本,yupSchema.validateSync,
它遵循与yupSchema.validate相同的语法
根据文档。
如果可能,同步运行验证并返回结果
值,或抛出 ValidationError
yupSchema.validateSync(input3, {strict: true})
创建了一个 REPL 供您使用不同的方法。
https://repl.it/@nithinthampi/UntriedImpracticalShoutcast
希望这会有所帮助!
相关文档链接。
https://hapi.dev/family/joi/?v=16.1.7
https://github.com/jquense/yup#usage