Pocket schema
Validates records against a schema.
Intended to be used within Pocket CMS
Table of Contents generated with DocToc
Getting started
Installation
Install pocket-schema
as dependency of your project
npm install --save pocket-schema
Usage
const Schema = ; // Create a schemaconst personSchema = additionalProperties: false fields: name: type: 'string' required: true origin: type: 'select' options: 'earth' 'mars' 'pluto' ; // Validate data against the schemaconst errors valid data = await personSchema;
Options
The validate method has the following signature :
validate(payload : object, opts : ValidationOptions = {})
The following validation options are available :
additionalProperties
Whether extra properties are allowed in the schema. Defaults totrue
ignoreRequired
If set to true, no error will be raised for missing properties marked asrequired:true
Supported types
-
any
-
array|list
- options:items?
A field definition of the expected array items
-
checkbox|boolean
-
date
- options:format?
The expected date format (defaults to YYYY-MM-DD)
-
datetime
-
email
- options:match?
A regular expression to match the email against
-
map
- options:items?
A field definition of the expected map items
-
multiselect
- options:options
List or options to select from. An async function can also be passed
-
number
- options:min?
Minimum allowed valuemax?
Maximum allowed value
-
object|json
- options:schema?
Schema used to validate the object against
-
password
- options:minLength?
The minimum length of the password
-
select|enum
- options:options
List or options to select from. An async function can also be passed
-
text|string
- options:minLength?
The minimum length of the stringmaxLength?
The maximum length of the stringmatch?
A regular expression to match the string against
-
time
-
timestamp
Custom validators
Additional validation can be performed if required by adding a validator
method to a field.
The expected signature is the following :
validatedata: any, field: Field: Errors|Promise<Errors>
The validate method takes the data and the field as arguments, and returns a list or errors
e.g
const Schema = ; // Create a schemaconst personSchema = additionalProperties: false fields: email: type: 'email' required: true { if !/@mycompany.com/ return 'Invalid email domain'; return null; } ;
Adding custom types
It is possible to register custom types with their custom validation.
Registering a pre-defined type will override the existing one.
const Schema = ; Schema;