Home

Awesome

obj-schema

Build Status Windows Tests Coveralls Coverage

Deps Status npm version npm downloads

Simple module to validate an object by a predefined schema

NPM

Written in coffee-script

INFO: all examples are written in coffee-script

Install

  npm install obj-schema

Initialize

	var Schema = require( "obj-schema" );

	uservalidator = new Schema( {
		"name": {
			type: "string",
			required: true
		},
		"email": {
			type: "email"
		},
		"age": {
			type: "number",
			default: 42
		}
	}, { name: "user" });

	console.log( uservalidator.validate( { name: "John", email: "john@do.com", age: 23 } ) ); // null
	console.log( uservalidator.validate( { name: "John", email: "john@do.com", age: "23" } ) ); // Error[`EVALIDATION_USER_NUMBER_AGE`: The value in `age` has to be a number]

Array Version

	var Schema = require( "obj-schema" );

	uservalidator = new Schema( [{
			key: "name",
			type: "string",
			required: true
		},{
			key: "email",
			type: "email"
		},{
			key: "age",
			type: "number",
			default: 42
		}]
	}, { name: "user" });

	console.log( uservalidator.validate( [ "John", "john@do.com", 23 ] ) ); // null
	console.log( uservalidator.validate( [ "John", "john@do.com", "23" ] ) ); // Error[`EVALIDATION_USER_NUMBER_AGE`: The value in `age` has to be a number]

The schema will check the given object against the defined rules and returns null on success or an error if the object is not valid. If the schema is configured to change the values it'll do this directly on the object reference.

Config

Schema-Types

General

number

Check if the value is of type number

string

Check if the value is of type string

boolean

Check if the value is of type boolean

array

Check if the value is of type array

object

Check if the value is of type object

email

Check if the value is of type string and is a valid email

enum

Check if the value is of type string and is one of the configured elements

schema

Check if the value is of type object and check against another given schema

timezone

Check if the value is of type string and is a valid moment timezone

Methods

.validate( object[, options] )

Validate the data obj and stop on the first error

Arguments

Return

( Null|Error ): Returns null on success and an error if the validation failed.

Example

	function create( data, cb ){
		var error = uservalidator.validate( data )
		if( error ){
			// handle the error
		}else{{
			// do your stuff
		}
	}

.validate( object[, options] )

Validate the data obj and stop on the first error

Arguments

Return

( Null|Error ): Returns null on success and an error if the validation failed.

Example

	function create( data, cb ){
		var error = uservalidator.validate( data )
		if( error ){
			// handle the error
		}else{{
			// do your stuff
		}
	}

.validateKey( key, value[, options] )

Validate olny one single key

Arguments

Return

Example

	function create( data, cb ){
		var errors = uservalidator.validateMulti( data )
		if( errors ){
			// handle the array of errors
		}else{{
			// do your stuff
		}
	}

( Null|[]Error ): Returns null on success and an array of errors if the validation failed.

.keys()

Returns an array of all keys within the schema.

Return

( Array ): Schema keys.

.validateCb( object[, options][, cb] )

A helper method to use it with a callback.

Arguments

Return

( Null|Error ): Returns null on success and an error if the validation failed.

Example

	function create( data, cb ){
		uservalidator.validateCb( data, function( err, data ){
			// do your stuff
		});
	}

.error( errtype, key, def, opt )

The internaly used method to generate the reponse error obj. You can define your own error obj. creator by defining a custom function in options.customerror.

Arguments

Return

( Null|Error ): Returns null on success and an error if the validation failed.

Example

	function create( data, cb ){
		uservalidator.validateCb( data, function( err, data ){
			// do your stuff
		});
	}

Error

This module uses a custom Error ( ObjSchemaError ) to add some meta data to the validation error response.

Arguments

Advanced example

This example in example.js. shows how to use the custom functions.

Testing

Node.js

To run the the node tests just call grunt test or npm test.

Browser

The browser test to use this module with browserify can simply executed with browserify-test

install: npm install -g browserify-test.

To test in browser just execute the following command within the project folder browserify-test --watch ./test/main.js Then follow the instructions ...

Headless

To test headless yo have to use is with phantomjs

install: npm install -g phantomjs

execute test: browserify-test ./test/main.js

Breaking Changes

Upgrade to 1.x

The arguments for the default function changed. A migration is only necessary if you used functions to calc the default on the fly.

Old:

Arguments: ( data, def )


var defaultName = function( data, def ){
    return "autogen-" + data.id;
};

var uservalidator = new Schema( {
    name: {
        type: "string",
        default: defaultName
    }
}, { name: "user" });

New:

Arguments: ( key, val, data, options )


var defaultName = function( key, val, data, options ){
    return "autogen-" + data.id;
};

var uservalidator = new Schema( {
    name: {
        type: "string",
        default: defaultName
    }
}, { name: "user" });

TODO

Release History

VersionDateDescription
1.6.22017-11-15fixed dependency licence issue by replacing the js-striphtml with striptags; updated dev dependencies
1.6.12017-02-20fixed failed build/publish
1.6.02017-02-20added feature to allow null for required values if nullAllowed: true
1.5.32017-02-09fixed: a array was accepted as type "object"
1.5.22017-02-09fixed: pass of missing customerror option to sub schemas
1.5.12017-02-09added path to error object to show the path through sub-schemas and optimized the generated name for sub schemas
1.5.02017-02-08it's now possible to nest a sub-schema direct within the parent as schema: { ... } / [ ... ]; Optimized tests for 100% codeverage
1.4.02016-11-14validate the basic input object for a object/array
1.3.02016-11-11added option customerror to be able to create your own error objects
1.2.32016-10-07Optimized sub-schema data type validation to check for object/array; use coveralls directly with coffee
1.2.22016-10-07Added badges and coveralls report
1.2.02016-10-07added length checks to array type; Made it possible to use an Array as schema to check the elements of an array; Optimized dev env.
1.1.32016-03-08updated dependencies. Especially lodash to version 4
1.1.22015-07-31removed dependency mpbasic for a smaller footprint within browserify
1.1.12015-07-14reduced error check operand to the values eq,neq,gt,gte,lt,lte,between
1.1.02015-07-14added check mode between/btw/>< to check a string length or numeric value.
1.0.02015-07-09added method .validateKey() to validate only one key. Added fnSkip definition method. Added optional options, that will be passed to the functions fnSkip and default. Changed arguments of default function.
0.3.02015-06-26added method .validateMulti() retrieve all validation errors at once
0.2.02015-06-25Changed strip tags module to be able to use this module with browserify
0.1.22015-06-19Added field definition (key def) to error.
0.1.12015-06-18Better validation error with custom fields. optimized readme.
0.1.02015-06-17Added string trim, added string length checks
0.0.12015-01-29Initial version

NPM

Initially Generated with generator-mpnodemodule

Other projects

NameDescription
rsmqA really simple message queue based on Redis
rsmq-workerHelper to simply implement a worker RSMQ ( Redis Simple Message Queue ).
redis-notificationsA redis based notification engine. It implements the rsmq-worker to savely create notifications and recurring reports
node-cacheSimple and fast NodeJS internal caching. Node internal in memory cache like memcached.
redis-sessionsAn advanced session store for NodeJS and Redis
connect-redis-sessionsA connect or express middleware to simply use the redis sessions. With redis sessions you can handle multiple sessions per user_id.
systemhealthNode module to run simple custom checks for your machine or it's connections. It will use redis-heartbeat to send the current state to redis.
task-queue-workerA powerful tool for background processing of tasks that are run by making standard http requests.
soyerSoyer is small lib for serverside use of Google Closure Templates with node.js.
grunt-soy-compileCompile Goggle Closure Templates ( SOY ) templates inclding the handling of XLIFF language files.
backlunrA solution to bring Backbone Collections together with the browser fulltext search engine Lunr.js

The MIT License (MIT)

Copyright © 2015 M. Peter, http://www.tcs.de

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.