3.0.0 • Published 7 years ago
tartaros v3.0.0
tartaros
Runtime type checks made easy.
How to
tartaros
only exports a single function.
var tartaros = require('tartaros');
var validate = tartaros({
username: 'String',
password: 'String',
rememberMe: 'Bool'
});
validate('foo');
// false
validate({
foo: 'bar'
});
// false
validate({
username: 'Arthur',
password: 'secret',
rememberMe: true
});
// true
validate({
username: 'Zaphod',
password: 'BB 4ever',
rememberMe: false,
thisIsOnePropertyTooMuch: 'foo'
});
// false
That function takes a schema as it's only argument and returns a function that validates its input according to that schema. A schema is either a String, an Array or an Object.
If the schema is a String, it must be on of String
, Number
, Bool
, Null
, Undefined
.
It resolves accordingly.
var validate = tartaros('Bool');
validate(true);
// true
validate(false);
// false
validate(/* anything else */);
// true
If the schema is an Object, tartaros
first of all checks if the passed data is an object.
Then it checks the types of all given keys.
var validate = tartaros({
msg: 'String',
nested: {
foo: 'String'
}
});
validate({
msg: 42,
nested: {
foo: 'bar'
}
});
// false
validate({
msg: 'hello',
nested: {
foo: 'bar'
}
});
// true
If the schema is an **Array**, `tartaros` first checks if the corresponding data is an `instanceof Array`.
Then it validates every item of that array with the schema given as the first element of the schema array.
```js
var validate = tartaros([ 'String' ]);
validate('foo');
// false
validate([ 'foo', 'bar' ]);
// true
validate([]);
// true