pocket-schema v1.1.0
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-schemaUsage
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'
});Options
The validate method has the following signature :
validate(payload : object, opts : ValidationOptions = {})
The following validation options are available :
additionalPropertiesWhether extra properties are allowed in the schema. Defaults totrueignoreRequiredIf set to true, no error will be raised for missing properties marked asrequired:true
Supported types
anyarray|list- options: *items?A field definition of the expected array itemscheckbox|booleandate- options: *format?The expected date format (defaults to YYYY-MM-DD)datetimeemail- options: *match?A regular expression to match the email againstmap- options: *items?A field definition of the expected map itemsmultiselect- options: *optionsList or options to select from. An async function can also be passednumber- options:min?Minimum allowed valuemax?Maximum allowed valueobject|json- options: *schema?Schema used to validate the object againstpassword- options: *minLength?The minimum length of the passwordselect|enum- options: *optionsList or options to select from. An async function can also be passedtext|string- options:minLength?The minimum length of the stringmaxLength?The maximum length of the string *match?A regular expression to match the string againsttimetimestamp
Custom validators
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;
}
}
}
});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 = 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;
}
});