nijikokun / Validator

JSON Schema validation library for Javascript / Node / Express.
159 stars 21 forks source link

Schema Validation for JavaScript

Barebones schema validation library for things such as database schemas, api data schemas, etc.

Install

$ npm install schema-validator

For browsers, download and include the script validator.js just as you would jquery or another script.

Implementations

Usage

You create a JSON Schema, where username is a field, and each key:value inside of it is an implementation in validator.

var schema = {
  username: {
    type: String,
    required: true,
    length: {
      min: 3,
      max: 36
    },
    test: /^[a-z0-9]+$/gi
  }
};

Setup a new Validator against your schema:

var validator = new Validator(schema);

Note there is also debugging support you can enable by adding the following line:

validator.debug = true;

Now we validate against some given information:

var check = validator.check({
  username: "Niji%kokun"
});

console.log(check);
Nesting

Nesting is supported, it's currently in a testing phase, as seen in the test file:

  belt: {
    type: Object,
    required: true,

    team: {
      type: Array,
      required: true,
      length: {
        min: 1,
        max: 6
      }
    },

    inventory: {
      type: Array,
      default: [],
      length: {
        max: 255
      }
    }
  }
Express Middleware Style:

Schema data will be put on the request object, req.validated, as an Object containing field : data information.

app.get('api/user/add', [ new Validator(schema.user, true) ], function (req, res) {
  res.send(200, req.validated);
});

or

app.get('api/user/add', [ (new Validator(schema.user)).middleware() ], function (req, res) {
  res.send(200, req.validated);
});

Creating an extension

Implementing a feature into Validator is easy, you set the field and a callback.

The callback supports a single argument options which contains valuable information.

Validator.implement("field", function (options) {
  if (options.data) {
    options.error("Data exists, this is wrong... or right! I don't know!");
  }

  // If you couldn't tell this gives an error back to the validator
  options.error("No check has been done against this key!");

  // and you can set custom field name for the error message object
  options.error("error-field", "This field hasn't been checked yet!");
});

After your implementation has been ran, the validator will check for errors, if found it will exit out and return the errors. You can pass along multiple errors per run, for an example check the test implementation.

Todo

Changelog

Version 3.3.0

Version 3.2.2

Version 3.2.1

Version 3.2.0

Version 3.1.0

Version 3.0.0

Version 2.0.0

Version 1.0.0