Validates records against a schema.
Intended to be used within Pocket CMS
Table of Contents generated with DocToc
Install pocket-schema
as dependency of your project
npm install --save pocket-schema
const Schema = require('pocket-schema');
// Create a schema
const personSchema = new Schema({
additionalProperties: false,
fields: {
name: {
type: 'string',
required: true
},
origin: {
type: 'select',
options: [
'earth',
'mars',
'pluto'
]
}
}
});
// Validate data against the schema
const { errors, valid, data } = await personSchema.validate({
name: 'john',
origin: 'earth'
});
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
-
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
Additional validation can be performed if required by adding a validator
method to a field.
The expected signature is the following :
validate(data: 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 = require('pocket-schema');
// Create a schema
const personSchema = new Schema({
additionalProperties: false,
fields: {
email: {
type: 'email',
required: true,
validate(email, field) {
if (!/@mycompany.com/.test(email)) {
return ['Invalid email domain'];
}
return null;
}
}
}
});
It is possible to register custom types with their custom validation.
Registering a pre-defined type will override the existing one.
const Schema = require('pocket-schema');
Schema.registerType('model', {
aliases: [
'record'
],
async validate(data, field) {
const recordId = data;
const record = await db.find({ id: recordId });
if (!record) {
return `Invalid id ${recordId}`;
}
return null;
}
});