Giter Club home page Giter Club logo

z-schema's Introduction

z-schema validator

NPM version Dependency Status

JSON Schema validator for Node.js (draft4 version)

Coded according to:

json-schema documentation, json-schema-core, json-schema-validation, json-schema-hypermedia

Passing all tests here (even optional, except zeroTerminatedFloats):

json-schema/JSON-Schema-Test-Suite

Will try to maintain this as much as possible, all bug reports welcome.

Basic Usage

var ZSchema = require("z-schema");
ZSchema.validate(json, schema)
    .then(function(report){
        // successful validation 
        // there might be warnings: console.log(report.warnings)
    })
    .fail(function(err){
        console.error(err.errors)
    })

Using traditional callback:

ZSchema.validate(json, schema, function(err, report){
    if(err){
        console.error(err.errors);
        return;
    }
    // successful validation 
    // there might be warnings: console.log(report.warnings)
})

If you need just to validate your schema, you can do it like this:

var validator = new ZSchema();
validator.validateSchema(schema)
    .then(function(report){
    })
    .fail(function(err){
    })

Or with Node.js style callback:

var validator = new ZSchema();
validator.validateSchema(schema, function (err, report) {
    if (err) ...
});

Remote references in schemas

Your schemas can include remote references that should be real URIs (more on that here) so validator can make a request and download the schema needed. Validator automatically caches these remote requests so they are not repeated with every validation.

In case you don't have a real server or you'd like to load files from different location, you can preload remote locations into the validator like this:

var fileContent = fs.readFileSync(__dirname + '/../json_schema_test_suite/remotes/integer.json', 'utf8');
ZSchema.setRemoteReference('http://localhost:1234/integer.json', fileContent);

http://localhost:1234/integer.json doesn't have to be online now, all schemas referencing it will validate against string that was passed to the function.

Advanced Usage

You can pre-compile schemas (for example on your server startup) so your application is not bothered by schema compilation and validation when validating ingoing / outgoing objects.

Promises:

var validator = new ZSchema();
validator.compileSchema(schema)
    .then(function(compiledSchema){
    })

Or callback:

var validator = new ZSchema();
validator.compileSchema(schema, function (err, compiledSchema) {
    assert.isUndefined(err);
    ...
});

Then you can re-use compiled schemas easily just the same way as non-compiled.

var validator = new ZSchema();
validator.validate(json, compiledSchema)
    .then(function(report){
        // ...
    })
    .fail(function(err){
        console.error(err.errors)
    })

Custom format validators

You can add validation for your own custom string formats like this: (these are added to all validator instances, because it would never make sense to have multiple functions to validate format with the same name)

var validator = new ZSchema();

ZSchema.registerFormat('xstring', function (str) {
    return str === 'xxx'; // return true/false as a result of validation
});

validator.validate('xxx', {
    'type': 'string',
    'format': 'xstring'
})
.then(function(){})
.fail(function(err){})

Custom validators can also be async:

Using promises:

ZSchema.registerFormat('xstring', function (str) {
    return Q.delay(1000).thenResolve(return str === 'xxx'); // return a promise for validation result
});

Using classic callback:

ZSchema.registerFormat('xstring', function (str, callback) {
    setTimeout(function(){
        callback(null, str === 'xxx');
        // or return custom error: callback(new Error('Bad, bad value!'))
    }, 2000)
});

Any exception thrown (or returned via classic callback) in custom validation function is written into validation error:

ZSchema.registerFormat('xstring', function (str) {
    throw new Error('Bad, bad value!');
});

And then expect errors to contain something like this:

[{ code: 'FORMAT',
    message: 'xstring format validation failed: Error: Bad, bad value!',
    path: '#/test',
    params: { format: 'xstring', error: [Error: Bad, bad value!] } } ]

Strict validation

When creating new instance of validator, you can specify some options that will alter the validator behaviour like this:

var validator = new ZSchema({
    option: true
});
  • noExtraKeywords: true/false

when true, do not allow unknown keywords in schema

  • noZeroLengthStrings: true/false

when true, always adds minLength: 1 to schemas where type is string

  • noTypeless: true/false

when true, every schema must specify a type

  • forceAdditional: true/false

when true, forces not to leave out some keys on schemas (additionalProperties, additionalItems)

  • forceProperties: true/false

when true, forces not to leave out properties or patternProperties on type-object schemas

  • forceItems: true/false

when true, forces not to leave out items on array-type schemas

  • forceMaxLength: true/false

when true, forces not to leave out maxLength on string-type schemas, when format or enum is not specified

Alternatively, you can turn on all of the above options with:

var validator = new ZSchema({
    strict: true
});

Pull requests

Avoid JSHint errors - settings for the JSHint are specified in .jshintrc. You can check for errors using grunt command which runs both jshint and mocha tests. Please check for errors before opening any pull requests.

Credits

z-schema's People

Contributors

zaggino avatar oleksiyk avatar

Watchers

Mackenzie Bodily avatar

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.