Schemator API

Define and validate rules, datatypes and schemata in NodeJS and in the Browser

bower version npm version Circle CI npm downloads License

Project Status

Latest Release: Latest Release

Status:

Dependency Status Coverage Status Codacity

Supported Platforms:

browsers

Quick Start

npm install --save js-data-schema or bower install --save js-data-schema

// NodeJS
var Schemator = require('js-data-schema');

// Browser
window.Schemator;

var schemator = new Schemator();

schemator.defineSchema('Person', {
  name: 'string'
});

var errors = schemator.validateSync('Person', { name: 'John' });

errors; // null

errors = schemator.validateSync('Person', { name: 50043 });

errors; // {
        //   name: [{
        //     rule: 'type',
        //     actual: 'number',
        //     expected: 'string'
        //   }]
        // }

Rules and Nullable Fields

Rules are extensible. Keys used in the schema definitions will be invoked with the value of the field and the value of the key. For instance, in the example below, the rules minLength and maxLength will be invoked.

Community & Links

Live Demos

Schemator API

new Schemator()

📘

Need help?

Want more examples or have a question? Post on the mailing list then we'll get your question answered and probably update this wiki.

Schemator#availableDataTypes()

Returns a list of available data types.

Schemator#availableRules()

Returns a list of available rules.

Schemator#availableSchemata()

Returns a list of available schemata.

Schemator#getDataType(name)

Return the data type definition function by the specified name.

Schemator#getRule(name)

Return the rule definition function by the specified name.

Schemator#getSchema(name)

Return the schema function by the specified name.

Schemator#removeDataType(name)

Remove the data type by the specified name.

Schemator#removeRule(name)

Remove the rule by the specified name.

Schemator#removeSchema(name)

Remove the schema by the specified name.

Schemator#defineDataType(name, typeDefinition)

Define a new data type.

Examples
var schemator = new Schemator();

schemator.defineDataType('NaN', function (x) {
  if (isNaN(x)) {
    return null;
  } else {
    return {
      rule: 'type',
      actual: typeof x,
      expected: 'NaN'
    };
  }
});

Schemator#defineRule(name, ruleFunc[, async])

Define a new rule.

Examples
var schemator = new Schemator();

schemator.defineRule('divisibleBy', function (x, divisor) {
  if (typeof x === 'number' && typeof divisor === 'number' && x % divisor !== 0) {
    return {
      rule: 'divisibleBy',
      actual: '' + x + ' % ' + divisor + ' === ' + (x % divisor),
      expected: '' + x + ' % ' + divisor + ' === 0'
    };
  }
  return null;
});

schemator.defineSchema('mySchema', {
  seats: {
    divisibleBy: 4
  }
});

var errors = schemator.getSchema('mySchema').validateSync({
  seats: 16
});

errors; //  null

errors = schemator.getSchema('mySchema').validateSync({
  seats: 17
});

errors; //  {
        //    seats: {
        //      errors: [ {
        //        rule: 'divisibleBy',
        //        actual: '17 % 4 === 1',
        //        expected: '17 % 4 === 0'
        //      } ]
        //    }
        //  }

Asynchronous rule:

var schemator = new Schemator();

schemator.defineRule('divisibleBy', function (x, divisor, cb) {
  
  // asynchronity here is fake, but you could do something async, like make an http request
  setTimeout(function () {
    if (typeof x === 'number' && typeof divisor === 'number' && x % divisor !== 0) {
      cb({
        rule: 'divisibleBy',
        actual: '' + x + ' % ' + divisor + ' === ' + (x % divisor),
        expected: '' + x + ' % ' + divisor + ' === 0'
      });
    }
    cb(null);
  }, 1);
}, true); // pass true as the third argument

schemator.defineSchema('mySchema', {
  seats: {
    divisibleBy: 4
  }
});

schemator.getSchema('mySchema').validate({
  seats: 16
}, function (errors) {
  errors; //  null

  schemator.getSchema('mySchema').validate({
    seats: 17
  }, function (errors) {
    errors; //  {
            //    seats: {
            //      errors: [ {
            //        rule: 'divisibleBy',
            //        actual: '17 % 4 === 1',
            //        expected: '17 % 4 === 0'
            //      } ]
            //    }
            //  }  
  });
});

The nullable rule

There is a special rule named "nullable" that, when true, will short-circuit rule processing when a null or undefined value is provided. However, it will also short-circuit when a value IS provided. To ensure that all rules are processed for nullable fields in which data is provided, return a false-y value other than null from a custom nullable rule.

var schemator = new Schemator();

schemator.defineSchema('Person', {
  name : { type: 'string', nullable: true, minLength: 5 }
});

// no errors
schemator.validateSync('Person', { name: undefined });

// no errors
schemator.validateSync('Person', { name: 'John' });

// redefine nullable rule
schemator.removeRule('nullable');
schemator.defineRule('nullable', function (x, _nullable) {
  if (x === null || x === undefined) {
    if (!_nullable) {
      // field was not nullable, return an error
      return {
        rule: 'nullable',
        actual: 'x === ' + x,
        expected: 'x !== null && x !== undefined'
      }
    } else {
      // field was nullable, no errors returned
      return null;
    }
  }

  // prevent schemator from short-circuiting the rest of the rules
  return undefined;
});

schemator.validateSync('Person', { name: 'John' });

// {
//   name: {
//     errors: [{
//       rule: 'minLength',
//       actual: '4 < 5',
//       expected: '4 >= 5'
//     }]
//   }
// }
Live Demo

Schemator#defineSchema(name, definition)

Define a new schema.

Examples
var schemator = new Schemator();

schemator.defineSchema('PersonSchema', {
  name: {
    first: {
      type: 'string',
      maxLength: 255
    },
    last: {
      type: 'string',
      maxLength: 255
    }
  },
  age: {
    type: 'number',
    max: 150,
    min: 0
  }
});

Schemator#validate(schemaName, attrs[, options], cb)

Shortcut for Schema#validate(attrs[, options], cb). See below.

Schemator#validateSync(schemaName, attrs[, options])

Shortcut for Schema#validateSync(attrs[, options]). See below.

Schemator#setDefaults(schemaName, attrs)

Shortcut for Schema#setDefaults(attrs). See below.

Schemator#getDefaults()

Shortcut for Schema#getDefaults(). See below.

Schemator#addDefaultsToTarget(schemaName, target[, overwrite])

Shortcut for Schema#addDefaultsToTarget(target[, overwrite]). See below.

stripNonSchemaAttrs(schemaName, target)

Shortcut for Schema#stripNonSchemaAttrs(target). See below.

Schema API

Example of how to create an instance of Schema.

Schemator#defineSchema(name, definition)

Schema#validate(attrs[, options], cb)

Validate a set of attributes according to the schema's definition.

Examples
var schemator = new Schemator();
var PersonSchema = schemator.defineSchema('person', {
  name: 'string'
});

PersonSchema.validate({
  name: 'John Anderson'
}, function (err) {
  err; // null
});

PersonSchema.validate({
  name: 5
}, function (err) {
  err;  //  {
        //    name: {
        //      errors: [{
        //        rule: 'type',
        //        actual: 'number',
        //        expected: 'string'
        //      }]
        //    }
        //  }
});

Schema#validateSync(attrs[, options])

Synchronous version of Schema#validate.

var schemator = new Schemator();
var PersonSchema = schemator.defineSchema('person', {
  name: 'string'
});

var errors = PersonSchema.validateSync({
  name: 'John Anderson'
});

errors; // null

errors = mySchema.validateSync({
  name: 5
});
errors; //  {
        //    name: {
        //      errors: [{
        //        rule: 'type',
        //        actual: 'number',
        //        expected: 'string'
        //      }]
        //    }
        //  }

Schema#setDefaults(attrs)

Define the default attributes for a schema, which can then be added to an object via Schema#addDefaultsToTarget described below.

Examples
var schemator = new Schemator();
var PersonSchema = schemator.defineSchema('person', {
  first: 'string',
  last: 'string',
  plan: 'string'
});

PersonSchema.setDefaults({
  first: '',
  last: '',
  plan: 'free'
});

Schema#getDefaults()

Return the defaults defined for the schema.

Examples
var schemator = new Schemator();
var PersonSchema = schemator.defineSchema('person', {
  first: 'string',
  last: 'string',
  age: 'number'
});

PersonSchema.setDefaults({
  first: '',
  last: '',
  age: 0
});

PersonSchema.getDefaults(); // {
                            //   first: '',
                            //   last: '',
                            //   age: 0
                            // }

Schema#addDefaultsToTarget(target[, overwrite])

Added the schema's default attributes to the target object, conditionally overwriting existing values.

Examples
var person = {
  first: 'John',
  plan: 'premium'
};

PersonSchema.addDefaultsToTarget(person);
 
person; // {
        //   first: 'John',
        //   last: '',
        //   plan: 'premium'
        // }

PersonSchema.addDefaultsToTarget(person, true);
 
person; // {
        //   first: '',
        //   last: '',
        //   plan: 'free'
        // }

Schema#stripNonSchemaAttrs(target)

String properties from the target object that are not defined in the schema.

Examples
var person = {
  first: 'John',
  plan: 'premium',
  nonSchema: 'value'
};

PersonSchema.stripNonSchemaAttrs(person);
 
person; // {
        //   first: 'John',
        //   plan: 'premium'
        // }

📘

License

The MIT License (MIT)

Copyright (c) 2013-2015 Jason Dobry

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.