backbone-validator
A super simple validator module for Backbone. It works both on the browser and nodejs.
Installing
In node:
npm install backbone-validator --save
In the browser make sure that you add the backbone-validator-min.js script after you have loaded both Underscore and Backbone. The minimised file is 2k.
Usage
var Backbone = ;var validator = ; var MyModel = BackboneModel; var model = ;model;model;
API
validator.create( schema )
To use this module you basically invoke validator.create()
passing it a
schema
object. This will return a function, and we set the model's validate
property to this function, so that Backbone
can use when setting attribute
values (ie: when model.save()
is invoked).
Defining a schema
A schema
object contains a property for each attribute
we want to validate,
the property name is the attribute
name and the value is an object containing
a set of rules.
In the example below we want to validate the ctime
, status
and message
attribues in our model, so our schema will look something like this:
validator;
Rules
Eache rule is declared passing it options
. This options
depend on each of
the rules (ie: for the required
rule options
is just a boolean, for the
oneOf
its an array, for custom
its a function and so on.
required
validator;
equal
validator;
regexp
validator;
oneOf
validator;
type
. Types:boolean
,number
,string
,date
,array
,email
,model
,collection
,url
anddomain
.
validator;
minLength
. Can be used with strings or arrays.
validator;
maxLength
. Can be used with strings or arrays.
validator;
recurse
. Can be used to do submodel validation.
validator;
Custom validation rules
var MyModel = BackboneModel;
Custom error messages
backbone-validator comes with default error messages that can be overriden.
validator;
TODO
- Add browser tests.