Git Product home page Git Product logo

jayschema's People

Contributors

adrianheine avatar alexbirkett avatar emschwartz avatar larose avatar markyen avatar mattisg avatar natesilva avatar pvorb avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jayschema's Issues

Leap seconds

The maximum value for date-time seconds should only consider leap-seconds as an option. The javascript Date object considers any 60th second invalid, so when validating an instance you're not getting any error, but when you then try to use the date in JS, it breaks.

Support custom error message

Currently all the useful error messages are hardcoded.
To support custom error message, e.g. localized, it would be great having an optional parameter defining the messages.

async validation with custom loader

At line 130

for (var index = 0, len = missing.length; index !== len; ++index) {
    var ref = missing[index];
    this._refsRequested.push(ref);
    this.loader(ref, loaderCallback.bind(this, ref));
}

you push ref to _refsRequested before loaderCallback. It's problematic when async validation.

One solution is:

JaySchema.prototype._loadMissingRefs = function(depth, callback) {
  var err;
  var missing = this._schemaRegistry.getMissingSchemas();

  // try not to request the same ref more than once
  missing = missing.filter(function(ref) {
    if (this._schemaRegistry.isRegistered(ref)) { return false; }
    if (this._refsRequested.indexOf(ref) !== -1) { return false; }
    return true;
  }, this);

  if (!missing.length) { return process.nextTick(callback); }

  // are we in too deep?
  if (!depth) {
    var desc = 'would exceed max recursion depth fetching these referenced ' +
      'schemas (set the maxRecursion property if you need to go deeper): ' +
      missing;
    err = new Errors.ValidationError(null, null, null, null, null,
      desc);
    return process.nextTick(callback.bind(null, err));
  }

  // fetch 'em
  var completedCount = 0;
  var totalCount = missing.length;
  err = null;

  var loaderCallback = function(ref, loaderErr, schema) {
    if (loaderErr) { err = loaderErr; }
    else { 
      this.register(schema, ref); 
      this._refsRequested.push(ref);
    }

    completedCount++;
    if (completedCount === totalCount) {
      if (err) {
        callback(err);
      } else {
        this._loadMissingRefs(depth - 1, function(err) { callback(err); });
      }
    }
  };

  for (var index = 0, len = missing.length; index !== len; ++index) {
    var ref = missing[index];
    this.loader(ref, loaderCallback.bind(this, ref));
  }

};

Access SchemaRegistry

Hi again!

It would be great, if one could get back a previously registered schema by its ID. There is SchemaRegistry.prototype.get(id) for this, but it's only accessible through JaySchema.prototype._schemaRegistry. What about making it accessible through JaySchema.prototype.get(id) just like you did with JaySchema.prototype.getMissingSchemas(). JaySchema.prototype.isRegistered(id) would be great to have, too.

JaySchema.validate callback consumes exceptions when custom loader is specified

In the following example with a custom loader specified, should.not.exist(errs); throws and the test cases never completes:

  describe('should fail but passes', function () {
        it('should work', function (done) {

            var schema = { 'type': 'integer', 'multipleOf': 8 };

            var loader = function (ref, callback) {
                process.nextTick(function () {
                    callback(null, schema);
                });
            };

            var js = new JaySchema(loader);

            var instance = 63;

            js.validate(instance, schema, function(errs) {
                should.not.exist(errs);
                done();
            });
        });
    });

Whereas a testcase without a custom loader completes as expected:

```describe('should fail', function () {
    it('should fail', function (done) {

        var schema = { 'type': 'integer', 'multipleOf': 8 };

        var js = new JaySchema();

        var instance = 63;

        js.validate(instance, schema, function(errs) {
            should.not.exist(errs);
            done();
        });
    });
});

Remove founded schema from _missingSchemas

Hi, I'm using your library for validationg my schemas.
I'm using a custom loader that loads files from a directory. Everything works good but, inside the callback, if I call getMissingSchemas() it gives me the references of the missing schemas it has already loaded.

I already have done a patch, but I'd like to understand if this is a bug (so I'll provide the fix) or this is a wanted behaviour.

Thanks
Dario

{$ref: refname} won't work

var JS = require('jayschema');
var js = new JS();
js.register({id: 'ref', type:'string'}, 'ref');
js.validate('this is a string', {$ref: 'ref'});

will give out some error:

{ 
    "instanceContext": "#/",
    "desc": "schema not available: anon-schema://36f98a1e368b3c68b099a53714594c0e9e465d18/schema-uri#"
}

This is because, when the schema object have no id, JaySchema will set a random id to it, and it named follow a protocol anon-schema://, when resolving the sub references, JaySchema will concat the sub ref with the root ref.

So, the issue also happend when I use a schema ref directly with a loader to load it.

function loader(ref, callback) { }
var js = new JS(loader);
js.validate({}, 'some-name', function(errs) {})

Is possible to use the shasum of object json string directly ?

Line numbers?

Is there any chance to line numbers in the validation errors?

Can't use as a linter presently.

Does Jayschema support concurrent validations?

I would like to construct a JaySchema object once, register my schemas, and then use it asynchronously to validate objects as needed. Does Jayschema support concurrent object validations?

Wrong behavior of 'allOf'

I think there is something wrong with the implementation of allOf.

I've got a base schema with common properties. Here is a simple example.

base.schema.json:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://example.org/base.schema.json",
  "title": "base",
  "description": "Base properties, common for all entities.",
  "type": "object",
  "required": [
    "created"
  ],
  "properties": {
    "created": {
      "description": "Date of creation",
      "format": "date-time",
      "type": "string"
    }
  }
}

I use that base schema in two other schemas.

concrete1.schema.json:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://example.org/concrete1.schema.json",
  "allOf": [ { "$ref": "http://example.org/base.schema.json" } ],
  "title": "base",
  "description": "Base properties, common for all entities.",
  "type": "object",
  "properties": {
    "id": {
      "description": "Name ID of a user",
      "type": "string"
    }
  }
}

concrete2.schema.json:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://example.org/concrete2.schema.json",
  "allOf": [ { "$ref": "http://example.org/base.schema.json" } ],
  "title": "base",
  "description": "Base properties, common for all entities.",
  "type": "object",
  "properties": {
    "id": {
      "description": "Email ID of a user",
      "type": "string",
      "format": "email"
    }
  }
}

I first register all schemas with JaySchema and then want to validate the following instance against concrete1.schema.json.

{
  "created": "2013-04-09T15:08:00.000Z",
  "name": "somename"
}

This will give me an error, saying that "somename" is not a valid email address. I would expect JaySchema to not use "format": "email", when I am validating against concrete1. By debugging JaySchema, I found out that it extends the properties of the base schema with the properties of concrete1 and concrete2. Thus properties.id gets overwritten. I think you should make a copy of the base schema before extending its properties instead.

async callback

Hi,
Do you consider to refactor the validate async callback to be according Node.js callback pattern as it would allow Promises?

By now I'm using a workaround

var Q = require('q');
var JaySchema = require('jayschema');
var js = new JaySchema();

js._validate = function(instance, schema, callback) {
    js.validate(instance, schema, function(err){
        callback(err, instance);
    })
}

Q.nfcall(js._validate, req.body, schema)
    .then(function(data){
        // validation success
    })
   .catch(function(err){
       console.log(err);
   })
;

Requireing a URI type?

How do I specify that a property match a valid URI format? I thought I would specify { format: 'uri' }, but that doesn't seem to trigger a validation error.
Thanks!

Asserts in validate callback ignored - test cases potentially broken

Asserts inside the JaySchema.validate callback are silently consumed. (I assume the exception thrown by should.not.exist(errs); is caught and ignored)

For example this case should fail but it passes:

 describe('should fail', function(done)
    {


        var js = new JaySchema();

        var instance = 65;
        var schema = { 'type': 'integer', 'multipleOf': 8 };

        js.validate(instance, schema, function(errs) {

            console.log(errs);
            should.not.exist(errs);

            done();
        });

    });

Is the use of $ref in the JSON being validated supported?

I posted this question to a closed issue accidently so not sure if anyone saw it. I am using $ref to pull in multiple values into the JSON being validated.

I wanted to confirm if Jayschema supports the use of $ref in the input to be validated. The errors I am getting would suggest it doesn't or more likely, I've not got the code quite right.

The data file looks like this

{
"Profile":{
"Type":"ebMS3_PModeOperationSet",
"Purpose":"Positive",
"Title":"PMode Operation Set for Superstream Entry Level",
"Description":"Covers ultra-light and light profiles",
"Version":{
"Major":0,
"Minor":1
}

},
"PModes" : [
{"$ref" : "http://test.compliancetest.net/get-profile?id=e7359f244623457286c672a4c1e7ae7dc8eb405b"},
{"$ref" : "http://test.compliancetest.net/get-profile?id=1f1c6bb0c31a2a5f78fc4757ad20f39e242b16ff"},
{"$ref" : "http://test.compliancetest.net/get-profile?id=92befc2c857eef0d0d912901dfedaa11e4269afe"}
]
}

and the schema looks like this

{
"$schema" : "http://json-schema.org/draft-04/schema#",
"title" : "ebMS3 PMode Operation Set Profile",
"Version" : {
"Major" : 0,
"Minor" : 1
},

"type" : "object",
"properties" : {
"Profile" : {"$ref" : "#/definitions/Profile/Profile"},
"PModes" : {"$ref" : "#/definitions/PMode/OperationSet"}

},
"required" : ["Profile", "PModes"],

"definitions" : {
"Types" : {
"NonNegativeInteger" : {"type" : "integer", "minimum" : 0},

    "MultipleOf8"               : {"allOf": [{"$ref" : "#/definitions/Types/NonNegativeInteger"}, { "multipleOf": 8}]},

    "NonEmptyString"            : {"type" : "string", "minLength" : 1},

    "URI"                       : {"type" : "string", "format" : "uri", "minLength" : 1},

    "Boolean"                   : {"type": "boolean"},

    "BooleanDefaultFalse"       : {"allOf": [{"$ref" : "#/definitions/Types/Boolean"}, { "default": false }]},

    "BooleanDefaultTrue"        : {"allOf": [{"$ref" : "#/definitions/Types/Boolean"}, { "default": true }]},

    "TimeUnit"                  : {"enum" : ["seconds", "minutes", "hours", "days", "weeks"]}
},

"Profile" : {
    "Type"                      : {"enum" : ["ebMS3_PModeOperationSet"]},

    "Purpose"                   : {"enum" : ["Positive", "Negative"], "default" : "Positive"},

    "Version" : {
        "type" : "object",
        "properties" : {
            "Major"             : {"$ref" : "#/definitions/Types/NonNegativeInteger"},
            "Minor"             : {"$ref" : "#/definitions/Types/NonNegativeInteger"},
            "Patch"             : {"$ref" : "#/definitions/Types/NonNegativeInteger"}
        },
        "required" : ["Major", "Minor"]
    },

    "Profile" : {
        "type" : "object",
        "properties" : {
            "Type"              : {"$ref" : "#/definitions/Profile/Type"},
            "Purpose"           : {"$ref" : "#/definitions/Profile/Purpose"},
            "Title"             : {"$ref" : "#/definitions/Types/NonEmptyString"},
            "Description"       : {"$ref" : "#/definitions/Types/NonEmptyString"},
            "Version"           : {"$ref" : "#/definitions/Profile/Version"}
        },
        "required" : ["Type", "Purpose", "Title", "Description", "Version"]
    }
},

"PMode" : {
    "OperationSet" : {
        "type" : "array",
        "items"                 : {"$ref" : "https://test.compliancetest.net/?download_profile_type=1&type_id=26"},
        "minItems" : 1
    }
}

}
}

the errors I am getting are

[ { instanceContext: '#/PModes/0',
resolutionScope: 'https://test.compliancetest.net/?download_profile_type=1&type_id=26#',
constraintName: 'required',
constraintValue: [ 'Profile', 'General' ],
desc: 'missing: Profile,General',
kind: 'ObjectValidationError' },
{ instanceContext: '#/PModes/1',
resolutionScope: 'https://test.compliancetest.net/?download_profile_type=1&type_id=26#',
constraintName: 'required',
constraintValue: [ 'Profile', 'General' ],
desc: 'missing: Profile,General',
kind: 'ObjectValidationError' },
{ instanceContext: '#/PModes/2',
resolutionScope: 'https://test.compliancetest.net/?download_profile_type=1&type_id=26#',
constraintName: 'required',
constraintValue: [ 'Profile', 'General' ],
desc: 'missing: Profile,General',
kind: 'ObjectValidationError' } ]

Is there a way to see what the schema validator thinks is the effective JSON it is validating? I'm thinking my data includes aren't right for some reason.

Thanks for your assistance.

Regards
Michael

TypeError: Cannot convert undefined or null to object

~/code/java/raml-test >jayschema json/request_address_correction.json schema/request_address_correction.schema.json
/usr/local/lib/node_modules/jayschema/lib/schemaRegistry.js:59
    if (!Object.prototype.hasOwnProperty.call(currentSchema, element)) {
                                         ^
TypeError: Cannot convert undefined or null to object
    at hasOwnProperty (native)
    at Function.SchemaRegistry._resolveJsonPointer (/usr/local/lib/node_modules/jayschema/lib/schemaRegistry.js:59:42)
    at SchemaRegistry.get (/usr/local/lib/node_modules/jayschema/lib/schemaRegistry.js:257:29)
    at run (/usr/local/lib/node_modules/jayschema/lib/suites/draft-04/index.js:93:43)
    at module.exports (/usr/local/lib/node_modules/jayschema/lib/suites/draft-04/keywords/_propertiesImpl.js:44:30)
    at run (/usr/local/lib/node_modules/jayschema/lib/suites/draft-04/index.js:126:28)
    at JaySchema._validateImpl (/usr/local/lib/node_modules/jayschema/lib/jayschema.js:227:10)
    at JaySchema.validate (/usr/local/lib/node_modules/jayschema/lib/jayschema.js:294:29)
    at Object.<anonymous> (/usr/local/lib/node_modules/jayschema/bin/validate.js:66:17)
    at Module._compile (module.js:460:26)

Looks like it's caused by a $ref with a filename. Here's the schema:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "id": "foo",
    "type": "object",
    "properties": {
    "order_id": { "type": "integer" },
    "shipping_address": { "$ref": "definitions.json#/address" }
    },
    "additionalProperties": false
}

When "definitions.json" is removed the error is gone, but the $ref cannot be found.

$ref with spaces does not work

Validation doesn't work if the reference path $ref has spaces, e.g. "#/definitions/some name".
Here is the next part of the code:

SchemaRegistry._resolveJsonPointer = function(schema, jp) {
   if (jp === '#') {
      return schema;
   }

  if (jp.slice(0, 2) !== '#/') {
    // not a JSON pointer fragment
    // (may be a valid id ref, but that’s not our problem here)
    return null;
  }
  var path = jp.slice(2).split('/');
  var currentSchema = schema;
  while (path.length) {
     var element = SchemaRegistry._decodeJsonPointer(path.shift());
     if (!Object.prototype.hasOwnProperty.call(currentSchema, element)) {
         return null;
     }
     currentSchema = currentSchema[element];
  }

  return currentSchema;
};

If the $ref has spaces, second param jp in the function is "#/definitions/some%20name".
As a result, local definition can`t be founded.
It would be nice if the author took the time to fix it.

Schema not available errors with http/https JSON references

I am attempting to reference one schema at a remote but absolute URL from a local schema, and am continually getting Schema not available errors. I replaced my URL with the one used in your samples, and verified I could access it in a browser.

Snippet from the local schema is

"PMode" : {
"OperationSet" : {
"type" : "array",
"items" : {"$ref" : "http://json-schema.org/geo"},
"minItems" : 1
}
}

and Validation trace shows

validation errors:
[ { instanceContext: '#/',
desc: 'schema not available: http://json-schema.org/geo#' },
{ instanceContext: '#/',
desc: 'schema not available: http://json-schema.org/geo#' },
{ instanceContext: '#/',
desc: 'schema not available: http://json-schema.org/geo#' } ]

(There are three rows in the instance I am attempting to validate)

I am suspecting something is preventing any access to the internet (both http and https URLS gave the same behaviour).

I am using node.js v0.10.21 and am invoking it from Eclipse. I've looked in project and workbench settings but can't see anything that would affect access to external schemas.

Any assistance to diagnose my issue would be appreciated.

Enum with null throwing error

I'm trying to write a schema with an enum property that allows a null value.

My schema declares:

"definitions": {
  "foo": {
    "type": "object",
    "properties": {
      "bar": { "enum": [ "a", "b", "c", null ] },
    }
  }
}

And I am receiving this error:

jayschema/lib/schemaRegistry.js:142
    if (Object.prototype.hasOwnProperty.call(currentObj, 'id') &&
                                        ^
TypeError: Cannot convert null to object
  at hasOwnProperty (native)
  at Function.SchemaRegistry._getSubObjectsHavingIds (jayschema/lib/schemaRegistry.js:142:41)
  at [object Object].SchemaRegistry.register (jayschema/lib/schemaRegistry.js:216:35)
  at [object Object].JaySchema.register (jayschema/lib/jayschema.js:73:40)

Is this expected?

Custom validation?

I apologize if this isn't the right forum for this, but I was wondering if there was a good way (without changing core functionality) to add comparison in the validation?

For example, I have a "startDate" and an "endDate" field, and I want to perform a check during validation that the "startDate" is prior to the "endDate".

Does this exist within the library already?

Registry not working properly

I've got some JSON Schema files with IDs like https://example.org/api/address.schema.json. This URL is not publicly available.

I'm trying to reference these schema definitions from another schema with something like

{
  "title": "user",
  "id": "https://example.org/api/user.schema.json",
  "properties": {
    "addresses": {
      "type": "array",
      "items": {
        "$ref": "https://example.org/api/address.schema.json"
      }
    }
    ...
  }
}

Because the URL is not online, I am registering all dependency schemas before validating the referencing schema. Nevertheless the value returned by validate() contains https://example.org/api/address.schema.json.

I'm not quite sure, if this is a bug or an error in my own code.

Error message is not clear in the case of "oneOf" usage

Hello
When using schema with "oneOf" part , The error message is not clear.
Here is the shema :

{
"oneOf": [
{
"$ref": "#/definitions/illegal"
},
{
"$ref": "#/definitions/legal"
}
],
"definitions": {
"illegal": {
"type": "object",
"properties": {
"propiska": {
"type": "string",
"enum": [
"no"
]
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": [
"firstName",
"lastName",
"propiska"
]
},
"legal": {
"type": "object",
"properties": {
"propiska": {
"type": "string",
"enum": [
"yes"
]
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
},
"address": {
"type": "object",
"properties": {
"street": {
"type": "string"
},
"city": {
"type": "string"
}
},
"required": [
"city"
]
}
},
"required": [
"firstName",
"lastName",
"address",
"propiska"
]
}
}
}

And here is instance , which fails in validation because required "firstName" property is missing
{
"firstName111":"kkkk",
"lastName":"llll",
"age1111": 30,
"address":{
"street":"Pall Mall",
"city":"London"
},
"propiska":"yes"
}

Here is code for validation :

console.log('synchronous result:', js.validate(instance, schema));

Here is validation result :

synchronous result: [ { instanceContext: '#',
resolutionScope: 'anon-schema://3699577afc51054fe9c66a9fb18d75dc7f692a89/#',
constraintName: 'oneOf',
constraintValue: [ [Object], [Object] ],
desc: 'does not validate against any of these schemas; must validate against one and only one of them',
kind: 'SubSchemaValidationError',
subSchemaValidationErrors:
{ '#/definitions/illegal': [Object],
'#/definitions/legal': [Object] } } ]

From the error message above is not clear , what is exact error.
In the case of simple schema (without usage "oneOf") error message :

synchronous result: [ { instanceContext: '#',
resolutionScope: 'anon-schema://ad55c1b70fa6557316d3b19574bcab746e90a426/#',
constraintName: 'required',
constraintValue: [ 'firstName', 'lastName', 'address', 'propiska' ],
desc: 'missing: firstName',
kind: 'ObjectValidationError' } ]

seems better.
The question is : is there something in the code when using schema with "oneOf"?
Thanks in advance

validate hang

given the following object and schema the validate function hang:

object:

{
    provider: { name: "1" }
}

schema:

{
        id:"/api/accounts/register",
        type: "object",
        oneOf: [ { $ref:"#/definitions/social" }, { $ref:"#/definitions/site" } ],


        definitions: {
            social: {
                additionalProperties: false,
                type: 'object',
                properties: {
                    provider: { enum: [ "facebook" ], required:true }
                }
            },
            site: {
                additionalProperties: false,
                type: 'object',
                properties: {
                    username: { type: "string", required:true },
                    password: { type: "string", required:true },

                    firstname: { type: "string" },
                    lastname: { type: "string" },
                    email: { type: "string" },
                    isSubscribed: { type: "boolean" }
                }
            }
        }
    }

Callback not invoked for undefined enum with custom loader

I ran into a case where an invalid schema was used that had an enum property with the array undefined. JaySchema didn't throw an exception or invoke the callback.

Here's a quick example to illustrate the problem:

var JaySchema = require('jayschema');
var instance = "hello";
var schema = { enum : undefined };

function loader(ref, callback) {
    console.log('loader referenced');
    callback('The schema referenced, ' + ref + ', could not be found.');
}

var js = new JaySchema(loader);  // if no loader is specified I get a synchronous exception
js.validate(instance, schema, function(errs) {
    if (errs) { console.error('async validation failed!', errs); }  // never called
    else { console.log('async validation OK!'); }  // also never called
});

console.log('validation started');

With 0.3.1 I get a stack trace on the console, but with 0.2.7 I didn't get anything at all (so at least that's an improvement).

validator._schemaRegistry not API ?

Sometimes I need to get a previously registered schema from the validator.
Is it ok to call myvalidator._schemaRegistry.get ? Could it be part of the API ?

"required" keyword in subschemas within definitions being ignored?

I have created two schema objects in the "definitions" section each of which "require" different properties, but at present Jayschema appears to be ignoring this and allowing anything in an instance.

Just wondered what I might be doing wrong? The schema is

{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {

    "Entity" : {
        "type" : "object", 
        "properties":{
            "oneOf" : [
                { "$ref": "#/definitions/ABNEntity" },
                { "$ref": "#/definitions/USIEntity" }
            ]
        }
    }
},
"required": ["Entity"],
"definitions" : {
    "ABNEntity" : {
        "properties":{
            "ABN": { "type": "string"},
            "MainName": { "type": "string"}
        },          
        "required" : ["ABN", "MainName"]            
    },
    "USIEntity" : {
        "properties":{
            "USI": { "type": "string"},
            "ProductName": { "type": "string"}
        },          
        "required" : ["USI", "ProductName"]         
    }
}

}

and an instance that still validates is

{
"Entity" : {
"ProductName" : "My product",
"ABN" : "335577654321"
}
}

Any assistance would be greatly appreciated.

format: 'date-time' doesn't work perfectly

Hi there,

When try to validate a string as "2001-05-06" with following schema:

type: 'string',
format: 'date-time'

I got an error says "constraintName : 'format', constraintValue : 'date-time', testedValue : '2001-05-06', desc : 'not a valid date-time per RFC 3339 secton 5.6'"

which looks incorrect. RFC 3339 section (BTW, a typo here) 5.6 (http://tools.ietf.org/html/rfc3339#section-5.6) supports previous date format:

full-date = date-fullyear "-" date-month "-" date-mday

Does it seem to be a bug of JaySchema?

Casting support

Hi

Please add casting support. I am using jayschema as a validator for incommung data, and everythign url-encoded has wrong primitive types, It needs to be casted before validation.

Best,
Oleg

format 'hostname' doesn't work correctly

String '127.0.0.1' validates against format 'hostname' and 'ipv4' which is no correct!

{
  "ipAddress": "127.0.0.1"
}

must be ok against

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "ipAddress": {
      "type": "string",
      "oneOf": [
        {
          "format": "hostname"
        },
        {
          "format": "ipv4"
        },
        {
          "format": "ipv6"
        }
      ]
    }
  }
}

but is not with JaySchema.

You can check with http://json-schema-validator.herokuapp.com/ or look at http://json-schema.org/example2.html

Validator is not detecting bad enum value

I was trying to validate an instance against the tincan.schema.json schema. My instance is:

{
    "id" : "fd41c918-b88b-4b20-a0a5-a4c32391aaa0",
    "actor" : {
        "objectType" : "Blowup",
        "name" : "Project Tin Can API",
        "mbox" : "mailto:[email protected]"
    },
    "verb" : {
        "id" : "http://adlnet.gov/expapi/verbs/created",
        "display" : {
            "en-US" : "created"
        }
    },
    "object" : {
        "id" : "http://example.adlnet.gov/xapi/example/simplestatement",
        "definition" : {
            "name" : {
                "en-US" : "simple statement"
            },
            "description" : {
                "en-US" : "A simple Experience API statement. Note that the LRS does not need to have any prior information about the Actor (learner), the verb, or the Activity/object."
            }
        }
    }
}

The tool reports valid even though the actor.objectType is not a valid value according to the schema.

Scheme url should be able to contain .. characters

The following fails, but should work

describe('passing schema url directly to validate function should work', function () {

it('.. is legal in a url', function (done) {

       var schema = { 'type': 'integer', 'multipleOf': 8 };

        var loader = function (ref, callback) {
            process.nextTick(function () {
                ref.should.equal('homemadescheme://host.com/../path');
                callback(null, schema);
            });
        };

        var js = new JaySchema(loader);

        var instance = 64;

        js.validate(instance, "homemadescheme://host.com/../path", function(errs) {
            console.log(errs);
            should.not.exist(errs);
            done();
        });
    });

Combining oneOf + enum causes the rejection of enum fields

Hi,

Given the following schema:

var schema  = {
    'type': 'object',
    'properties': { 
        'foo': { 
            'oneOf': [
                {
                    'type': 'integer'
                }, 
                {
                    'type': {'enum': ['bar', 'baz']}
                }
            ]
        }
    },
    'additionalProperties': false
};

The following does not work as I would expect:

js.validate({foo: 'bar'}, schema);

More precisely, the error reads:

js.validate({foo: 'bar'}, schema)[0].subSchemaValidationErrors
{ 'sub-schema-1': 
   [ { [Error]
       instanceContext: '#/foo',
       resolutionScope: 'anon-schema://e4d7cffef264084baaaceaa96437195d3e63275c/#/properties/foo/oneOf/0',
       constraintName: 'type',
       constraintValue: 'integer',
       testedValue: 'string' } ],
  'sub-schema-2': 
   [ { [Error]
       instanceContext: '#/foo',
       resolutionScope: 'anon-schema://e4d7cffef264084baaaceaa96437195d3e63275c/#/properties/foo/oneOf/1',
       constraintName: 'type',
       constraintValue: [Object],
       testedValue: 'string' } ] }

Apparently, the foo property is wrongly recognized as a string instead of one of the possible enum values.

Thanks.

Speed: the validator is-my-json-valid is thousands of times faster then jayschema

I've been investigating JSON-schema validators. And contributing to the benchmarks at the JSON-schema validators themisand JSCK. According to the benchmarks included in both themis and JSCK. Jayschema is extreemely slow. And is-my-json-valid is the fastest of all at least 5 times faster than the runner up, and thousands of times faster than jayschema.

Add method to sanitize input

The sanitize method should take a schema and an input json. It should then output a version of the input that corresponds to the schema or throw an error if not possible.

For example it should:

  1. Remove fields that are present but not defined in the schema
  2. Keep fields that are correct according to the schema
  3. Remove fields that don't match the schema but are optional
  4. Throw an error if a required field is missing

Optionally it would also be good to have a strict mode so that in case 2) an error would be thrown as well.

Format "uri" is not throwing errors

This should throw an error, but it doesn't:

var JaySchema = require('jayschema');
var js = new JaySchema();
var instance ={ "url": "invalid"};
var schema = {
    "type": "object",
    "properties": {
        "url": {
            "type": "string",
            "format": "uri"
        }
    }
}

js.validate(instance, schema, function(errs) {
    if (errs) {
        console.error(errs);
    }
    else {
        console.log('async validation OK!');
    }
});

Non-supported schemas throw cryptic error

I get the following error when I try to validate a schema which specifies a $schema that is not the default http://json-schema.org/draft-04/schema#:

var JaySchema = require('jayschema');
var js = new JaySchema();
var instance = 64;
var schema = { "$schema": "http://json-schema.org/schema#", "type": "integer" }
console.log('synchronous result:', js.validate(instance, schema));
TypeError: undefined is not a function
    at JaySchema._validateImpl (/Users/colin/test_jay/node_modules/jayschema/lib/jayschema.js:179:10)
    at JaySchema.validate (/Users/colin/test_jay/node_modules/jayschema/lib/jayschema.js:245:29)
    at repl:1:39
    at REPLServer.self.eval (repl.js:110:21)
    at repl.js:249:20
    at REPLServer.self.eval (repl.js:122:7)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface.<anonymous> (readline.js:322:12)

This is caused by the lines:

  var testRunner = testRunners[schema.$schema || DEFAULT_SCHEMA_VERSION];
  return testRunner(config);

in Jayschema.prototype._validateImpl.

testRunners is only ever:

var testRunners = {
  'http://json-schema.org/draft-04/schema#': require('./suites/draft-04')
};

While most people who are rolling their own schemas will not run into this, it is confusing to those who have other JSON Schema versioned schemas which they are validating.

If you think this is a valid issue, I'm happy to open a PR that adds a check to Jayschema.prototype.validate something like:

  if (schema.$schema && !testRunners[schema.$schema]) {
    desc = 'JSON Schema version: ' + schema.$schema + ' not supported by JaySchema'
    err = new Errors.ValidationError(null, '#', null, null, null, desc);
    if (callback) {
      return process.nextTick(callback.bind(null, [err]));
    } else {
      return [err];
    }
  }

Support browserify; get rid of dynamically loaded dependencies

Or at least allow overriding of this behavior. I'd like to use this on the client and server, but as written it doesn't work with browserify, due to the behavior of loading schema validators dynamically:

In lib/suites/draft-04/index.js, line 122:

  // test all applicable schema properties
  var props = getApplicableTests(config);
  for (var index = 0; index < props.length; ++index) {
    var prop = props[index];
    var fn = require('./keywords/' + prop + '.js');
    errors = errors.concat(fn(config));
  }

Browserify can't resolve these because they are evaluated at run-time. Would it be possible to add a configuration option to override this and support your own (static) requires implementation that would work with frontend delivery tools like browserify better?

I can submit a PR if this is something that would be accepted.

Validator not responding using extends: $ref

Here is a test case written in coffeescript:

testSchema2 = {
      "id": "http://ref.schema",
      "type":"object",
      "properties":{
         "name": {
            "type":"string"
         }
      }
    }

    testSchema1 = { 
      "name": "Invoice", 
      "type": "object", 
      "properties": { 
          "id": { 
              "type": "integer" 
          }, 
          "delivery": { 
              "extends": {"$ref": "http://ref.schema"}, 
              "required": true 
          } 
      } 
    }

    js.register(testSchema2) 
    js.register(testSchema1)
    testInstance = {
      "id":1
    }
    console.log "test schema", js.validate(testInstance, testSchema1)

It should "not" validate because the validation of the delivery is now required from the "extends". Or maybe I am doing something wrong.

It also seems to run out of memory if the ref's are of any significant size.

FATAL ERROR: JS Allocation failed - process out of memory

Validating schemas themselves

Howdy,

This is a really great library, thank you.

I am puzzled why jayschema would accept [I've tested a few other validators as well]

var res = js.validate( {}, { "dtype": "integer", "multipleOf": 8 } );

Note dtype which isn't part of the spec, yet this test passes. I must be missing something obvious. I would expect the schema to be checked if invalid.

error: Undefined should be an object

var schema = {
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Result",
  "type": "object",
  "properties": {
    "additional_info": {
      "description": "More info",
      "type": "object",
    }
  },
  "additionalProperties": false
}

var instance = {additional_info: undefined};

var JaySchema = require('jayschema');
var js = new JaySchema();


js.validate(instance, schema, function(errs) {
  if (errs) { console.error(errs); }
  else { console.log('validation OK!'); }
});

/*
 * [ { [Error]
 *     instanceContext: '#/additional_info',
 *     resolutionScope: 'anon-schema://8acc7aec06a4b148e96a2130384cea97b268413d/#/properties/additional_info',
 *     constraintName: 'type',
 *     constraintValue: 'object',
 *     testedValue: 'undefined' } ]
 */

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.