backbone-schema
A minimalistic and lightweight schema validator for Backbone models. Loosely inspired by Mongoose's schema validation. Feel free to fork, modify, and contribute to your needs. Pull requests and issues are welcome.
npm install backbone-schema
Usage
Can be used in the browser or the server. Just include backbone-schema in your
project and define a schema
property in your models.
See Backbone's documentation for more information.
Example
See tests.js for more examples.
Basic example
var Backbone = ;; var User = BackboneModel; var liam = ; // Emits an error because "username" is not defined.liam; // Good to goliam; // Emits an error because "nickname" must be a stringliam; // Good to goliam; // Emits an error because "joined" must be a date.
Extended example
var Backbone = ;; var Message = BackboneModel;
Options
Below is a list of options available for each attribute in the schema.
required
If true
, the field must be defined.
Type: Boolean
, Default: false
validators
An array of validator functions that will be passed the value of this field
and ran. You can access the current model within these functions using this
.
Type: Array
, Default: []
type
If defined, the field must be of the specified type. May be a string or a function.
Type: Function
or String
, Default: null
choices
An array of objects. If defined, then the value of this field must be in this array.
Type: Array
, Default: []
Strict mode
Strict mode will invalidate the model if there are attributes in it that don't
exist in the schema. It is off by default, but you can enable it by defining
_isStrict
in the top-level of your schema.