Schema

API ReferenceSchema

Module used to validate structures.

Access it with:

const { Schema } = Neft;

Source

Class SchemaError()

Raised by Schema::validate() if given data doesn't pass the schema.

Access it with:

var Schema = require('schema');
var SchemaError = Schema.Error;

Source


constructor()

Parameters
  • schema — Object

Creates a new Schema instance used to validate data.

Specify schema validators for each of the accepted property.

new Schema({
    address: {
        type: 'string'
    },
    delivery: {
        optional: true,
        type: 'boolean'
    }
});

Source


schema

Type
Object

Saved schema object from the constructor.

It's allowed to change this object in runtime.

Source


validate()

Parameters
  • data — Object
Returns
Boolean

Validates the given data object by the schema.

Returns true if the data is valid, otherwise throws an SchemaError instance.

var schema = new Schema({
  age: {
    type: 'number',
    min: 0,
    max: 200
  }
});

console.log(utils.catchError(schema.validate, schema, [{}])+'');
// "SchemaError: Required property age not found"

console.log(utils.catchError(schema.validate, schema, [{name: 'Jony'}])+'');
// "SchemaError: Unexpected name property"

console.log(utils.catchError(schema.validate, schema, [{age: -5}])+'');
// "SchemaError: Minimum range of age is 0"

console.log(schema.validate({age: 20}));
// true

console.log(utils.tryFunction(schema.validate, schema, [{age: -1}], false));
// false

console.log(utils.tryFunction(schema.validate, schema, [{age: 5}], false));
// true

Nested properties

Use dot in the property name to valdiate deep objects.

var schema = new Schema({
  obj: {
    type: 'object'
  },
  'obj.prop1.name': {
    type: 'string'
  }
});

console.log(utils.catchError(schema.validate, schema, [{obj: {prop1: {name: 123}}}])+'');
// "SchemaError: obj.prop1.name must be a string"

console.log(schema.validate({obj: {prop1: {name: 'Lily'}}}));
// true

This function uses utils.get() internally.

var schema = new Schema({
  names: {
    array: true
  },
  'names[]': {
    type: 'string'
  }
});

console.log(utils.catchError(schema.validate, schema, [{names: [123, null]}])+'');
// "SchemaError: names[] must be a string"

console.log(schema.validate({names: ['Lily', 'Max']}));
// true

Source

results matching ""

    No results matching ""