oferei / json-gate

A friendly, fast JSON schema validator
MIT License
100 stars 16 forks source link

type with an array of schemas not supported #20

Closed Filirom1 closed 11 years ago

Filirom1 commented 11 years ago

Hi

This stackoverflow solutions does not work with json-gate: http://stackoverflow.com/questions/9029524/json-schema-specify-field-is-required-based-on-value-of-another-field

var schema = {
    "type": [
        {
            "title": "New Zealand (no postcode)",
            "type": "object",
            "properties": {
                "country": {"enum": ["NZ", "NZL", "NEW ZEALAND"]},
            }
        },
        {
            "title": "Other countries (require postcode)",
            "type": "object",
            "properties": {
                "country": {"enum": ["FR"]},
                "postcode": {"required": true}
            }
        },
    ],
    "properties": {
        "country": {
            "type" : "string",
            "default" : "AUS"
        },
        "postcode": {
            "type" : "string"
        }
    }
};

var instance1 = {
  country: "NZ"
};

var instance2 = {
  country: "FR",
  postcode: "42320"
};

var badInstance = {
  country: "FR"
};

var jsonschema = require('json-schema');
console.log(jsonschema.validate(instance1, schema));
console.log(jsonschema.validate(instance2, schema));
console.log(jsonschema.validate(badInstance, schema));

var schema = require('json-gate').createSchema(schema);
schema.validate(instance1);
schema.validate(instance2);
schema.validate(badInstance);

The output is:

{ valid: true, errors: [] }
{ valid: true, errors: [] }
{ valid: false,
  errors:
   [ { property: 'undefined.postcode',
       message: 'is missing and it is required' } ] }

/root/smartdata/smart-admin-api/node_modules/json-gate/lib/valid-schema.js:10
        throw new Error('Schema' + getName(names) + ': ' + attribFullName + ' is ' +
              ^
Error: Schema: 'type' attribute is an array when it should be a string
    at throwInvalidType (/root/smartdata/smart-admin-api/node_modules/json-gate/lib/valid-schema.js:10:8)
    at assertType (/root/smartdata/smart-admin-api/node_modules/json-gate/lib/valid-schema.js:16:4)
    at module.exports (/root/smartdata/smart-admin-api/node_modules/json-gate/lib/valid-schema.js:281:2)
    at new Schema (/root/smartdata/smart-admin-api/node_modules/json-gate/lib/json-gate.js:6:2)
    at Object.module.exports.createSchema (/root/smartdata/smart-admin-api/node_modules/json-gate/lib/json-gate.js:14:9)
    at Object.<anonymous> (/root/smartdata/smart-admin-api/toto.js:48:35)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
oferei commented 11 years ago

yup, a bug. thanks for the info! but this was already noted in bug #18.