Node.js Input Validator module
Simple Node.js module to validate and filter input parameters.
Usage
npm install --save @springworks/input-validator
Include module and use validation functions:
var input_validator = require('input-validator');
var filtered = input_validator.filterParams({ foo: 1, bar: 2, baz: 3 }, ['foo', 'bar']);
API
filterParams(params, allowed)
Ensures a params
object only has the allowed
parameters:
var filtered = input_validator.filterParams({ foo: 1, bar: 2, baz: 3 }, ['foo', 'bar']);
assert(filtered.length === 2);
isMissingParams(params, required)
Checks if any of the required params are missing.
var is_missing_params = input_validator.isMissingParams({ foo: 1 }, ['foo', 'bar']);
assert(is_missing_params === true);
missingParams(params, required)
Checks if any of the required params are missing. Returns any missing params in an array.
var missing_params = input_validator.missingParams({ foo: 1 }, ['foo', 'bar']);
assert(missing_params.length === 1);
isTypesValid(params, types)
Checks that the parameters have the correct datatype. Returns true if all params are of valid types.
var has_valid_params = input_validator.isTypesValid({foo: 'baz', bar: 'foz'}, {foo: String, bar: Boolean});
assert(has_valid_params === false);
invalidTypeParams(params, types)
Checks that the parameters have the correct datatype. Returns parameters that don't have the correct datatype in an array. Returns an empty array if all parameters are of the correct datatype.
var invalid_params = input_validator.invalidTypeParams({foo: 'baz', bar: 'foz'}, {foo: String, bar: Boolean});
assert(invalid_params.length === 1);
getType(obj)
Returns a string with the name of the datatype of obj
.
assert(input_validator.getType('this is a string') === 'String');
assert(input_validator.getType(1337) === 'Number');
assert(input_validator.getType(true) === 'Boolean');
assert(input_validator.getType([]) === 'Array');
assert(input_validator.getType({}) === 'Object');
getType(obj)
Returns a string with the name of the datatype of obj
.
assert(input_validator.getType('this is a string') === 'String');
assert(input_validator.getType(1337) === 'Number');
assert(input_validator.getType(true) === 'Boolean');
assert(input_validator.getType([]) === 'Array');
assert(input_validator.getType({}) === 'Object');
validateSchema(obj, schema, resource_name, options)
Validates obj
against a Joi.schema
. It will filter unknown
keys. It will throw an error if validation fails.
var schema = Joi.object().keys({
'username': Joi.string().required(),
'password': Joi.string().required()
}),
validated;
validated = Joi.validate({
'username': 'foo',
'password': 'bar'
}, schema);
Tests
Run npm test
to run complete unit tests with Istanbul code coverage.