简体   繁体   English

描述性的Hapi / Joi验证错误

[英]Descriptive Hapi/Joi validation error

I've been trying to implement Joi in our node application (joi as standalone, not with hapi) and it seems to validate the schema properly but the error is always the same 我一直在尝试在我们的节点应用程序中实现Joi(joi作为独立的,而不是hapi),它似乎正确地验证了模式,但错误始终是相同的

[ValidationError: value must be an object] 
name: 'ValidationError',
details:
[ { message: 'value must be an object',
   path: 'value',
   type: 'object.base',
   context: [Object] } ],
_object:.....

I never get the specifics on which key it failed on and description of why it failed. 我从来没有得到关于它失败的密钥的具体信息以及它失败原因的描述。

this is a sample schema I'm using: 这是我正在使用的示例模式:

exports.workersSchema =
{
workers: joi.array({
    id: joi.string().alphanum(),
    wID: joi.object({
        idValue: joi.string().alphanum()
    }),
    person: {
        governmentIDs: joi.array({itemID: joi.string().alphanum()}),
        legalName: joi.object({
            givenName: joi.string(),
            middleName: joi.string(),
            preferredSalutations: joi.array(
                {
                    salutationCode: {
                        longName: joi.string()
                    }

                }
            ),
            preferredName: joi.object().keys({
                FormattedName: joi.string()
            }),
        }),
        birthDate: joi.string().alphanum()
    }
})
}

And this is the json object I'm sending : 这是我发送的json对象:

{"workers" : [        
        {
          "id" : "",
          "wID" : {
            "idValue" : ""
          },
          "person" : {
            "governmentIDs":[{
                "itemID": "asd" 
            }],
            "legalName":{
              "givenName" : "PA",
              "middleName" : "",
              "preferredSalutations" : [{
                "salutationCode" : {
                  "longName" : ""
                    }
              }],
              "preferredName" : {
                "FormattedName" : ""
              },
              "birthDate" : ""
        }]
}

What am i doing wrong here? 我在这做错了什么? I even tried to follow something on the blog and while the examples were showing detailed info I never got anything besides 我甚至尝试在博客上关注某些内容,而示例显示的详细信息我从未得到任何其他内容

"value must be an object"

It validates it correctly but when it sees a misfit value it just gives that error and nothing else. 它可以正确验证它,但是当它看到错配值时,它只会给出错误而没有别的。

Also, if you look at the 'wID' section it has a 'idValue' object but when I get rid of the idValue and just put a alphanum right on the wID key, it also passes the validation. 此外,如果您查看'wID'部分,它有一个'idValue'对象但是当我摆脱idValue并且只是在wID键上放置一个alphanum时,它也会通过验证。

ps. PS。 When validating keys that are objects. 验证作为对象的键时。 Do I have to validate it with 我必须验证它吗?

key: Joi.object({
  a:Joi.string()
})

or can I just do?: 或者我可以这样做?:

key: {
  a:Joi.string()
}

Thank you so much for the help! 非常感谢你的帮助!

I think there's a couple of issues. 我认为有几个问题。 First of all, make sure that the object you're validating against is indeed an object with a workers key. 首先,确保您要验证的object确实是具有workers键的object The validation seems to be suggesting that you're not providing an object for this base value (an array perhaps)? 验证似乎表明你没有提供这个基值的对象(也许是一个数组)?

Also in a few instances I think you're using the API incorrectly (eg joi.array(...) is not valid). 同样在少数情况下,我认为你错误地使用了API(例如joi.array(...)无效)。 I've modified your schema to work how I think you intended. 我已经修改了你的架构,以便按我的想法工作。 If not, post a sample object and I'll amend. 如果没有,发布一个样本对象,我会修改。

var schema = {
    workers: Joi.array().required().includes({
        id: Joi.string().alphanum(),
        wID: {
            idValue: Joi.string().alphanum()
        },
        person: {
            governmentIDs: Joi.array().includes(Joi.string().alphanum()),
            legalName: {
                givenName: Joi.string(),
                middleName: Joi.string(),
                preferredSalutations: Joi.array().includes(Joi.string()),
                preferredName: {
                    formattedName: Joi.string()
                },
            },
            birthDate: Joi.string().alphanum()
        }
    })
};

Here's a valid object for that schema: 这是该架构的有效对象:

var goodExample = {
    workers: [
        {
            id: 'bhdsf78473',
            wID: {
                idValue: 'idvalue1'
            },
            person: {
                governmentIDs: ['id1', 'id2'],
                legalName: {
                    givenName: 'Johnny',
                    middleName: 'Michael',
                    preferredSalutations: ['sir', 'Dr'],
                    preferredName: {
                        formattedName: 'Sir Johnny Michael Smith'
                    }
                },
                birthDate: '2411986'
            }
        }
    ]
};

Here's an invalid one: 这是一个无效的:

var badExample = {
    workers: [
        {
            id: 'bhdsf7^£$%^£$%8473',   // Here's the issue
            wID: {
            },
            person: {
                governmentIDs: ['id1', 'id2'],
                legalName: {
                    givenName: 'Johnny',
                    middleName: 'Michael',
                    preferredSalutations: ['sir', 'Dr'],
                    preferredName: {
                        formattedName: 'Sir Johnny Michael Smith'
                    }
                },
                birthDate: '2411986'
            }
        }, 
    ], 
};

Joi should give nice detailed output for Joi.assert(example, schema); Joi应该为Joi.assert(example, schema);提供很好的详细输出Joi.assert(example, schema); :

$ node index.js

/.../node_modules/Joi/lib/index.js:121
            throw new Error(message + error.annotate());
                  ^
Error: {
  "workers": [
    {
      "wID": {},
      "person": {
        "governmentIDs": [
          "id1",
          "id2"
        ],
        "legalName": {
          "givenName": "Johnny",
          "middleName": "Michael",
          "preferredSalutations": [
            "sir",
            "Dr"
          ],
          "preferredName": {
            "formattedName": "Sir Johnny Michael Smith"
          }
        },
        "birthDate": "2411986"
      },
      "id" [1]: "bhdsf7^£$%^£$%8473"
    }
  ]
}

[1] workers at position 0 fails because id must only contain alpha-numeric characters
    at root.assert (/.../node_modules/Joi/lib/index.js:121:19)
    at Object.<anonymous> (/.../index.js:57:5)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:929:3

NOTE: This answer is using Joi 5.1.2 (API: https://github.com/hapijs/joi/blob/v5.1.0/README.md ). 注意:这个答案使用的是Joi 5.1.2(API: https//github.com/hapijs/joi/blob/v5.1.0/README.md )。 Joi.array().includes() will be dropped in the next release in favour of Joi.array().items() 将在下一个版本中删除Joi.array().includes()以支持Joi.array().items()


The object that you posted is not a valid JavaScript object because it's missing some closing } brackets. 您发布的对象不是有效的JavaScript对象,因为它缺少一些关闭}括号。 Here's the valid version: 这是有效版本:

var obj = {
  "workers" : [{
    "id" : "",   // <-------- Shouldn't be empty
    "wID" : {
      "idValue" : ""
    },
    "person" : {
      "governmentIDs":[{
        "itemID": "asd" 
      }],
      "legalName":{
        "givenName" : "PA",
        "middleName" : "",
        "preferredSalutations" : [{
          "salutationCode" : {
            "longName" : ""
          }
        }],
        "preferredName" : {
          "FormattedName" : ""
        },
      },
      "birthDate" : ""
    }
  }]
};

If I validate that with my provided schema, I get the following message (using Joi 5.1.0): 如果我使用我提供的架构验证,我收到以下消息(使用Joi 5.1.0):

[1] workers at position 0 fails because id is not allowed to be empty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM