【问题标题】:How to Modify Existing Keys in Joi Object如何修改 Joi 对象中的现有键
【发布时间】:2019-06-23 13:38:16
【问题描述】:

Joi 验证不支持修改现有对象键。

我正在对父类和子类使用 Joi 验证。对父项的验证是对所有子项的基本验证,但每个子项都有特定的限制或附加字段。 我希望能够只获取我的父 Joi 对象并能够修改现有键以适应某些限制。

//Declare base class with an array at most 10 elements
const parent = {
    myArray: Joi.array().max(10)
}
//Now declare child with minimum 1 array value
const child = parent.append({
    foo: Joi.string(),
    myArray: Joi.array().min(1).required()
})

上面的代码按预期工作 - 这意味着子对象不会将 .limit(10) 限制应用于父对象。 但是,我希望它做到这一点。我确定 append 不是在这里使用的正确功能,但我不确定如何执行此操作。 我希望生成的子验证看起来像:

const child = {
    foo: Joi.string(),
    myArray: Joi.array().max(10).min(1).required()
}

【问题讨论】:

    标签: node.js validation joi


    【解决方案1】:

    你试过了吗:

    const child = parent.append({
        foo: Joi.string(),
        myArray: parent.myArray.min(1).required()
    });
    

    刚试过:

    const Joi = require('joi');
    
    const parent = {
      x: Joi.array().max(10).required()
    };
    
    const child = Object.assign({}, parent, {
      x: parent.x.min(1).required(),
      y: Joi.string()
    });
    
    Joi.validate({
      x: [],
      y: 'abc'
    }, child); // fails as .min(1) not satisfied
    
    Joi.validate({
      x: [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1],
      y: 'abc'
    }, child); // fails as .max(10) not satisfied
    
    Joi.validate({
      x: [1],
      y: 'abc'
    }, child); // OK
    

    在 Node v8.10.0 上尝试使用新的 npm i joi(包装上写着:"joi": "^14.3.1")。还是您给出的示例太琐碎而无法反映您的真实情况?

    【讨论】:

    • 是的,Joi 不支持从父对象访问密钥。这基本上就是我想要做的事情
    • 刚刚尝试过,按预期工作......请参阅上面的编辑。
    • 啊,我使用Joi.object() 来创建我的父母/孩子(我的示例没有正确显示)。这样做会删除通过parent.key 访问元素的能力。但是你这样做的方式,只有香草对象,效果很好。谢谢!
    • 在极少数情况下,您必须处理预先构建的 Joi 对象(例如获取声明为嵌套在数组中的项目),然后您可以使用脏方法:x: parent._inner.children.find((e) => { return e.key === 'x'; }).schema.min(1).required()。 (我记得我必须这样做一次,我刚刚测试过它仍然可以在最新版本上运行,而不会改变 parent.x 的行为。)Enjoi!
    • 啊,好吧,那个 dirty 修复实际上对我有很大帮助——我只是把它扔到一个辅助函数中。谢谢!
    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 2019-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 1970-01-01
    • 2017-08-05
    • 2011-10-17
    相关资源
    最近更新 更多