我在试着比较乔依和尤普。我们的前端客户反应使用formik,这也使用yup。现在,我们正在开发后端api端。
不管怎么说,乔依或尤特会做这样的事情吗?
value = {
'en' : 'teststes'
'fr' : 'aaaaa'
...
}我想验证这个值是否是字符串。这个属性可能只是'en',或者其他一些我目前还不知道的语言支持。
我也想知道是否有一种同步的方法。我知道是的迫使我做异步的
发布于 2019-10-18 06:48:57
如果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”,以及值必须为string的未知键,则可以使用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});就像你说的,这是一个回报。因此,您应该使用返回承诺的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
https://stackoverflow.com/questions/58443015
复制相似问题