Skip to content

This package validates a javascript object against a schema given by the user

Notifications You must be signed in to change notification settings

anuj3918/object-validator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

38 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

kasper - a very simple object schema validator

Build Status Coverage Status

A javascript package which helps you validate your objects against a specified schema.

Application

This package is useful in validations for cases such as:

  1. In applications where you frequently interact with external services and I/O is in form of objects.
  2. In code flows where object needs to be validated for any undefined/null values before executing main function logic.
  3. In places where you need to set default values if something mismatches from schema (configuration variables)
  4. In places where you write a final schema and partially validate your object as it keys get added to it as the code flows.

Further explanation: https://medium.com/@anujkumargupta/why-validate-your-objects-with-kasper-8aa7eb3093e1

Installation

npm install --save kasper

Github repository

https://github.com/anuj3918/object-validator.git

Code example

const kasper = require('kasper');

const schema = {
	id: { keyType: [ 'string' ], notAllowed: [ 'abc001' ], regExp: /abc/g },
	mode: { keyType: [ 'string' ], allowed: [ 'card' ] },
	amount: { keyType: [ 'number' ], min: 0, default: 0 },
	currency: { keyType: [ 'string' ], default: 'usd', allowed: [ 'inr', 'usd' ], notAllowed: [ '' ] },
	cardDetails: {
		number: { keyType: [ 'string' ], size: [ 12, 16, 20 ] },
		cvc: { keyType: [ 'number' ], isInteger: true },
		month: { keyType: [ 'number' ], range: [ 1, 12 ], isInteger: true },
		year: { keyType: [ 'number' ], range: [ 2018, 2050 ], isInteger: true }
	},
	errors: { keyType: [ 'error', 'null' ], default: null },
	datetime: { keyType: [ 'date', 'string' ], default: new Date() },
	birthday: { keyType: [ 'date' ], range: ['25/11/1995 00:00:00', '31/12/2050 23:59:59'] },
	countries: { keyType: [ 'array' ], allowed: [ [ 'india', 'nepal' ], [ 'england', 'iceland' ] ], notAllowed: [ [] ] }
};

const payload = {
	id: 'abc1234',
	mode: 'card',
	amount: 123.45,
	currency: '',
	cardDetails: {
		number: '4444555566667777',
		cvc: 987,
		month: 2,
		year: 2020
	},
	errors: undefined,
	datetime: null,
	birthday: new Date(),
	countries: ['india', 'nepal']
};

const options = {
	matchPartialSchema: true,    // default: false
	strictMatch: false,	     // default: false
	setDefaultValues: true	     // default: true
};

// You can omit the last parameter i.e. options if you want to use default options only
const response = kasper.validate(schema, payload, options);
console.log(response);

// Output
let output = {
	err: null,
	message: 'Validations successful',
	result: {
		id: 'abc1234',
		mode: 'card',
		amount: 123.45,
		currency: 'usd',
		cardDetails: { number: '4444555566667777', cvc: 987 month: 2, year: 2020},
		errors: null,
		datetime: 2018-08-30T19:30:18.386Z,
		birthday: 2018-08-30T19:30:18.386Z,
		countries: ['india', 'nepal']
	}
};

Schema flags with decsription

Flag Value Description
keyType ['number', 'boolean', 'string', 'object', 'array', 'null', 'date', 'error'] mandatory Specify the types for key as an array
allowed ['india', 'us', 'china'] (array of values) Checks if value of key is among these values
notAllowed ['', 'delhi', 'mumbai' ] (array of values) Checks if value of key is not among these values
size [1,3,5] (Array of integers) Checks if length of string/array is in one of the given sizes. Use only with string/array
regExp /hello/g (a valid regular exp) Checks if string matches a regular expression
max 100 (any numerical value) Checks if number value is not greater than max
min 1 (any numerical value) Checks if number value is not less than min
range [1, 10] Number: Checks if number lies in the specified range (both limits inclusive)
range ['25/11/1995 00:00:00', '31/12/2050 23:59:59'] Date: Checks if date lies in the specified range (both limits inclusive). Date format should be 'DD/MM/YYYY HH:mm:ss'
isInteger true (any boolean value) Checks if number value is an integer
default "Narendra Modi" (any type of value) Sets a default value to key if error encountered while validating this key
strictObject false (boolean) If false, treats date/error/null/array as type 'object' (javascript native behaviour)

Options with decsription

Flag Default Value Description
matchPartialSchema false If true, checks only the keys present in object with that in schema
strictMatch false If true, checks if object does not contain any extra keys than those mentioned in schema
setDefaultValues true If false, does not set default value to a key even if default value is specified

Contributions

You can add any of the above features into this package and create a pull request. For any further queries, write to [email protected]

Keywords

kasper object validation schema model external nodejs javascript typescript flow datatype type-validation json validator casper blueprint

About

This package validates a javascript object against a schema given by the user

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published