Home

Awesome

is-my-schema-valid

build status npm version Dependency Status Download Count

Simple function that validates data according to JSONSchema spec (under the hood it is powered by is-my-json-valid which uses code generation to be extremely fast).

Install

npm install is-my-schema-valid --save

Usage

validate(data: Object, schema: Object, options: ?Object) -> { valid: Boolean, errors: ?Array<Object> }

Validate data object against passed schema. Function alwats returns object with boolean valid field, if valid is false there will be additional errors field with the list of error objects.

Options

If you search for express middleware take a look on is-express-schema-valid.

Example

import validate from 'is-my-schema-valid';

const schema = {
    email: {
        type: 'string',
        required: true,
        format: 'email'
    },
    password: {
        type: 'string',
        required: true,
        minLength: 1
    }
};

const notValidData = {email: 'foo', password: 'bar'};
const result1 = validate(notValidData, schema);
console.log(result1.valid); // false
console.log(result1.errors); // list of errors

const validData = {email: 'foo@bar.com', password: '123456'};
const result2 = validate(validData, schema);
console.log(result2.valid); // true

Define schemas

When defining a schema you are able to pass a plain object. In this case is-my-schema-valid will automagically populate your schema with default object properties:

const schema = {
    foo: {
        type: 'string',
        required: true
    }
};

// will be passed to validator as:
// { 
//   type: 'object', 
//   required: true, 
//   additionalProperties: false, 
//   properties: { 
//     foo: { 
//       type: 'string', 
//       required: true 
//     }
//   }
// }

In other cases when you need a different type use a full schema. For example, when payload needs to be an array:

const schema = {
    type: 'array',
    uniqueItems: true,
    items: {
        type: 'number'
    }
};

// it will be used as is by validator

Formats

There are several additional formats added for easy validating the requests:

In the example below we can ensure that id is valid MongoDB ObjectId:

import validate from 'is-my-schema-valid';

const schema = {
    id: {
        type: 'string',
        format: 'mongo-object-id'
    }
};

Just a reminder that there are default built-in formats supported by JSONSchema:

JSONSchema

In order to get comfortable with JSONSchema spec and its' features I advice you to check the book "Understanding JSON Schema" (also PDF version) or look at examples.


MIT Licensed