simple schema validation

simple schema validation
```
npm install @amphibian/validate
`javascript`
var {validate} = require('@amphibian/validate');
property with a string describing the expected type.`javascript
// String schema
{type: 'string'}
`type can be any of the following: any, undefined, boolean, number, string, regexp, array, object, date, function, promise.#### schema.optional
Provide
boolean optional if validate shouldn't validate input when it is undefined.`javascript
// NOTE Will not throw
validate(undefined, {type: 'string', optional: true});
`#### schema.test
Provide
function test to do your own validation after validate has succeeded. It is given three arguments: input, objectPath, and objectPathArray. objectPath is a readable string showing the location of the error in the provided schema. objectPathArray is the array representation of that string that can be passed onto other validate functions.`javascript
// NOTE Will throw custom error
validate('password', {
type: 'string',
test: (input, objectPath) => {
if (input.length < 10) {
throw new Error(Password too short at "${objectPath}"!);
}
}
});
`$3
Special property properties that describe children of the object.`javascript
{
type: 'object',
properties: {
someChild: {type: 'string'},
otherChild: {type: 'number', optional: true}
}
}
`$3
Special property indices that describe children of the array.`javascript
{
type: 'array',
indices: {type: 'string'}
}
`Usage
The
validate function takes two arguments: The variable you would like to validate, and the schema it should match. validate throws on error.`javascript
var {validate} = require('@amphibian/validate');try {
validate({}, {type: 'string'});
} catch (error) {
console.log(error.code); // > type_error
}
`Errors
If the schema validation fails, an
@amphibian/error will be thrown. The error object is an Error instance with a few extra properties, and looks somewhat like this:`javascript
{
message: 'Invalid Input (unknown_schema_type): schema.type undefned',
status: 400,
type: 'invalid_input',
code: 'unknown_schema_type',
data: ['schema.type', 'undefned']
}
`The first index of
error.data is the path to where the error was found.Advanced schemas
To build more advanced and complex schemas, utilize the
any type with custom test parameters.`javascript
var {validate, expectOneToSucceed} = require('@amphibian/validate');
var schema = {
type: 'any',
test: (input, objectPath, objectPathArray) => {
try {
expectOneToSucceed([
() => validate(input, {type: 'object'}, objectPathArray),
() => validate(input, {type: 'array'}, objectPathArray)
]);
} catch (error) {
throw new Error(Use Object or Array at "${objectPath}"!);
}
}
};validate({}, schema);
``