acornejo/jjv

TypeError: Cannot call method 'hasOwnProperty' of undefined

Opened this issue · 3 comments

When a JSON schema has a required key without a corresponding type: "object", and the JJV validator is passed undefined for that object, JJV throws TypeError: Cannot call method 'hasOwnProperty' of undefined.

It appears that JJV calls hasOwnProperty() on the undefined value before checking that the value is in fact an object, resulting in this error.

According to json-schema.org:

When the primitive type of the instance cannot be validated by a given keyword, validation for this keyword and instance SHOULD succeed.

Perhaps the correct behavior in this case is that when there's a required: ["foo"] without a corresponding type: "object", validation will simply succeed?

To reproduce the error, run coffee test.coffee:

# test.coffee
jjv = require "jjv"

validator = jjv()

# NOTE: No `type: "object"` for this schema:
validator.addSchema "testSchema",
  required: ["foo"]

validator.validate "testSchema", undefined

...and you will get the following error: TypeError: Cannot call method 'hasOwnProperty' of undefined.

since jjv throws, this is most definitely an error, and I will gladly fix it.

However, we should first agree on what the correct output should be on that schema when called on undefined; My gut feeling is to fail, since the type undefined does NOT have a "foo" property. However, your argument about why it should succeed also seems pretty solid.

Would you mind opening an issue in https://github.com/json-schema/JSON-Schema-Test-Suite to discuss this? Once we have a definitive answer from the folks at json-schema I can proceed to fix it (pull requests to fix this are also welcome btw).

Great idea! I actually posted to the json-schema repo itself, since I'm realizing the official JSON Schema draft actually doesn't specify whether the type keyword is required. (If it were, then you could safely say that undefined being passed to a schema with required: ["foo"] is valid, since the schema itself is invalid.)

I get the same exception with the following example

var env = jjv();

var errors = env.validate({
    type: 'object',
    properties: {
        people: {
            type: ['object', 'null'],
            properties: {
                firstName: {type: 'string'},
                lastName: {type: 'string'}
            },
            required: ['firstName', 'lastname']
        },
    }
 }, {
    people: null
});

Is the project still maintained? I could make a pull request if you plan to merge it and tag a new version