0.0.1 • Published 12 years ago

model.js v0.0.1

Weekly downloads
8
License
-
Repository
github
Last release
12 years ago

model.js

Lightweight library for declaring/validating models/schemas. It has no dependencies and is focused on validating javascript objects only. Models defined can easily be reused on server side or on browser, providing a central place to validate your data.

This library is based on Backbone and jQuery-validation(some of the builtin validation functions are adaptations from jQuery-validation(a few regexes were copied).

Use cases:

  • Store metadata about your domain objects
  • Store validation for your data. Can be shared between server/client
  • Easy conversion of form-generated JSON to an object containing properties with the correct types.

Instalation

$ npm install model.js

Basic concepts

  • Model: Associates each propertyName to map of rules. Can be used to verify that an object is conforming to its rules.
  • Rule: key/value pair where the key is the rule identifier and the value is some parameter that will be passed to the handler associated with the identifier.
  • Handler: function that contains the rule logic and decides if there's a schema error.

Usage

var Model = require('model.js');

'Model' represents an abstract data model/schema. To do anything useful you need to extend the Model with properties. Each property can be associated with set of rules.

Example:

> var Model = require('model.js');

> var Person = Model.extend({
... id: { type: 'integer', required: true },
... name: { type: 'string', minlength: 4, maxlength: 20 },
... birthdate: { type: 'date' },
... });

> var Customer = Person.extend({
... 'contact.email': { email: true, required: true },
... 'contact.phone': { type: 'string' },
... 'contact.address': { type: 'string' }
... });

// 'validate' returns a map of property keys/validation errors
> Person.validate({})
{ id: [ 'Required' ] }

// the 'required' rule will have preference over other rules
> Customer.validate({})
{ 'contact.email': [ 'Required' ], id: [ 'Required' ] }

> Person.validate({id: 'not a number'})
{ id: [ 'Expecting integer' ] }

// Models inherit rules and other options
> Customer.validate({id: 5.7, contact: {email: 'not an email'}})
{ 'contact.email': [ 'Invalid email address' ],
  id: [ 'Expecting integer' ] }

// types are weakly enforced, if the value can be converted then its ok:
> Customer.validate({id: '100', contact: {email: 'customer@company.com'}})
null

// Normally 'validate' will only validate. Pass 'true' as the second 
// argument to apply conversions if needed
> var customer = {id: '100', birthdate: '2000-10-10', contact: {email: 'customer@company.com'}}
> Customer.validate(customer, true)
> customer
{ id: 100,
  birthdate: Tue, 10 Oct 2000 00:00:00 GMT,
  contact: { email: 'customer@company.com' } }

See the 'tests' directory for more examples.

To run the tests

$ npm install -d
$ make test