【问题标题】:Joi How to allow unknown property as long as the value is stringJoi 只要值为字符串,如何允许未知属性
【发布时间】:2019-10-18 18:31:41
【问题描述】:

我试图在 joi 或 yup 之间进行比较。 我们的前端客户端反应使用formik,它也使用yup。 现在我们正在开发后端 api 端。

无论如何,joi 或 yup 是否可以做这样的事情

value = {
 'en' : 'teststes'
 'fr' : 'aaaaa'
 ...
}

我想验证该值是否为字符串。 该属性可能只有“en”,或者我目前不知道的其他语言支持。

我也想知道是否有办法同步执行此操作。我知道是的,强迫我异步进行

【问题讨论】:

    标签: javascript hapijs joi yup


    【解决方案1】:

    如果value 需要stringobject(形状为{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的thencatch子句来处理成功和失败。

    但也有同步版本,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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-30
      • 2019-06-01
      • 2022-11-12
      • 2021-05-13
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多