Minimalist JavaScript object validation library.
PropChecker is packaged on npm:
$ npm install propchecker
var config = {
foo: [PropChecker.isRequired, PropChecker.isString],
nested: {
bar: PropChecker.isNumber,
arr: PropChecker.isArray,
anotherArray: PropChecker.isArrayOf(PropChecker.isNumber)
}
};
var obj = {
foo: 'some string',
nested: {
bar: 123,
arr: ['element1', 'element2'],
anotherArray: [1, 2, 3, 4]
}
};
var errorHandler = function(errors) {
console.log(errors);
};
PropChecker.validate(obj, config, errorHandler);
Check the property value is not a null and not an undefined
Check the property value is a string
Check the property value is a number
Check the property value is a boolean
Check the property value is a number
Check the property value is an object
Check the property value is a date
Check the property value is a function
Check the property value is a regexp
Check the property value is a error
Check the property value is an array with specific elements type. Type specified through any PropChecker validator. Basic example:
var config = {
arrayWithString: PropChecker.isArrayOf(PropChecker.isString),
arrayWithArrayWithNumbers: PropChecker.isArrayOf(PropChecker.isArrayOf(PropChecker.isNumber))
};
var obj = {
arrayWithString: ['some string', 'another string'],
arrayWithArrayWithNumbers: [[1], [2, 3], [4, 5]]
};
PropChecker.validate(obj, config);
Check the property value is equal to primitive, using strict equality operator inside. Basic example:
var config = {
age: PropChecker.isEqual(18)
};
var obj = {
age: 18
};
PropChecker.validate(obj, config);
Check the property value to inherits another class. Basic example:
class BaseClass {}
class AnotherOne extends BaseClass {}
var config = {
some: PropChecker.isInherits(BaseClass)
};
var obj = {
some: AnotherOne
};
PropChecker.validate(obj, config);
You can define your own PropCheck validator. Type checker function should return null, when the value is valid, or an error instance, when the value is invalid. Basic example:
var myValidator = new PropChecker(function(propName, propValue) {
if (propValue > 10) {
return new TypeError(propName + ' is invalid');
}
return null;
});
var config = {
age: myValidator
};
var obj = {
age: 9
};
PropChecker.validate(obj, config);