Use NPM to include Schemafy in your project:
$ npm install --save schemafy
For Node or Browserify:
var Schemafy = require('schemafy');
For AMD or static browser:
Not supported yet.
Schemas are defined with Schemafy, which returns an object constructor function:
var userSchema = {
type: "object",
additionalProperties: false,
properties: {
username: {
type: "string"
},
isAdmin: {
type: "boolean"
}
}
};
var User = Schemafy(userSchema);
Schemas are implemented using JSON Schema v4. It can define many complex structures and requirements. Schemafy has two signficiant restrictions when defining schemas:
The root schema type must be "object," otherwise Schemafy can't build an object.
Schemafy does not support JSON Schema's tupled defintions for arrays.
name (string) - New schema's name
schema (object) - JSON Schema schema
Returns a new schema constructor based on the schema.
name (string) - New schema's name
newSchema (object) - JSON Schema schema
Returns a new schema constructor based on the original schema and the properties of the new schema. The new schema is merged into the original schema's definition; therefore, it can be partially defined; however, any array structures are replaced by the new defintion, not merged.
Returns the JSON Schema definition for the schema.
target (object) - POJO to validate
Returns an array of errors, if any, how the target fails validation with the schema.
Schemas are used to create new POJOs:
var user = new User(); // => {}
The objects belong to their schema:
user instanceof User // => true
The objects can be modified like any other object:
user.username = "Teddy";
user.isAdmin = true;
New objects can be loaded from a source and validated:
var user = new User(badDataFromDb, { coerce: false });
// => { username: 123, isAdmin: "" }
user.__validate();
// => [ 'instance.username is not of a type(s) string',
// 'instance.isAdmin is not of a type(s) boolean' ]
New POJOs can be created with all fields pre-initialized:
var user = new User({}, { createAll: true });
// => { username: "", isAdmin: false }
source (object) - Optional initialization source POJO
options (object) - Optional hash of options
options.coerce (boolean, default true) - Attempt to coerce any properties that do not match type into required type.
options.createAll (boolean) - All properties are created from defaults if not initialized from a source.
Returns a new instance of type Schema.
Returns the POJO's properties as a JSON string.
Returns an array of errors, if any, how the target fails validation with the schema.