Backbone.validation
A validation plugin for Backbone.js that validates both your model as well as form input
Install / Use
/learn @thedersen/Backbone.validationREADME
Backbone.Validation
A validation plugin for Backbone.js that validates both your model as well as form input.
Introduction
Good client side validation is an important part of giving your users a great experience when they visit your site. Backbone provides a validate method, but it is left undefined and it is up to you to override it with your custom validation logic. Too many times I have seen validation implemented as lots of nested ifs and elses. This quickly becomes a big mess. One other thing is that with libraries like Backbone, you hold your state in a Model, and don't tie it to the DOM. Still, when validating your models you probably want to inform your users about errors etc., which means modifying the DOM.
Backbone.Validation tries to solve both these problems. It gives you a simple, extensible way of declaring validation rules on your model, and overrides Backbone's validate method behind the scene. And, it gives you a nice hook where you can implement your own way of showing the error messages to your user.
If you are using node.js on the server you can also reuse your models and validation on the server side. How cool is that?
Backbone.Validation is a bit opinionated, meaning that you have to follow some conventions in order for it to work properly.
Download and source code
You can download the raw source from GitHub, see the annotated source or use the links below for the latest stable version.
Standard builds
- Development: backbone-validation.js 22.7kb
- Production: backbone-validation-min.js 2.7kb gzipped
AMD builds
- Development: backbone-validation-amd.js 24.2kb
- Production: backbone-validation-amd-min.js 2.8kb gzipped
Node.js builds
npm install backbone-validation
Bower builds
bower install backbone-validation
Getting started
It's easy to get up and running. You only need to have Backbone (including underscore.js) in your page before including the Backbone.Validation plugin. If you are using the default implementation of the callbacks, you also need to include jQuery.
The plugin is tested with, and should work with the following versions of
- Backbone >= 1.0.0
- Underscore >= 1.4.3
Configure validation rules on the Model
To configure your validation rules, simply add a validation property with a property for each attribute you want to validate on your model. The validation rules can either be an object with one of the built-in validators or a combination of two or more of them, or a function where you implement your own custom validation logic.
Validating complex objects is also supported. To configure validation rules for objects, use dot notation in the name of the attribute, e.g 'address.street'.
Example
var SomeModel = Backbone.Model.extend({
validation: {
name: {
required: true
},
'address.street': {
required: true
},
'address.zip': {
length: 4
},
age: {
range: [1, 80]
},
email: {
pattern: 'email'
},
someAttribute: function(value) {
if(value !== 'somevalue') {
return 'Error message';
}
}
}
});
// validation attribute can also be defined as a function returning a hash
var SomeModel = Backbone.Model.extend({
validation: function() {
return {
name: {
required: true
}
}
}
});
See the built-in validators section for a list of the validators and patterns that you can use.
Specifying error messages
Backbone.Validation comes with a set of default error messages. If you don't like to use those, you can either override them, or you can specify error messages where you declare validation rules on the model.
You can specify an error message per attribute by adding a msg property like this:
MyModel = Backbone.Model.extend({
validation: {
email: {
required: true,
pattern: 'email',
msg: 'Please enter a valid email'
}
}
});
Or, you can specify an error message per validator, by adding an array of validators like this:
MyModel = Backbone.Model.extend({
validation: {
email: [{
required: true,
msg: 'Please enter an email address'
},{
pattern: 'email',
msg: 'Please enter a valid email'
}]
}
});
The msg property can also be a function returning a string.
Using form+model validation
The philosophy behind this way of using the plugin, is that you should be able to reuse your validation rules both to validate your model and to validate form input, as well as providing a simple way of notifying users about errors when they are populating forms.
Note that Backbone.Validation does not provide any automatic/two-way binding between your model and the view, that's up you to implement (you can for instance use Backbone.stickit).
Before you can start using form validation, you need to bind your view.
Validation binding
The validation binding code is executed with a call to Backbone.Validation.bind(view). There are several places that it can be called from, depending on your circumstances, but it must be called after your model or collection has been initialized.
// Binding when rendering
var SomeView = Backbone.View.extend({
render: function(){
Backbone.Validation.bind(this);
}
});
// Binding when initializing
var SomeView = Backbone.View.extend({
initialize: function(){
Backbone.Validation.bind(this);
}
});
// Binding from outside a view
var SomeView = Backbone.View.extend({
});
var someView = new SomeView({model: new SomeModel()});
Backbone.Validation.bind(someView);
// Binding to a view with an optional model
var myModel = new Backbone.Model();
var SomeView = Backbone.View.extend({
initialize: function(){
Backbone.Validation.bind(this, {
model: myModel
});
}
});
// Binding to a view with an optional collection
var myCollection = new Backbone.Collection();
var SomeView = Backbone.View.extend({
initialize: function(){
Backbone.Validation.bind(this, {
collection: myCollection
});
}
});
Binding to view with a model
For this to work, your view must have an instance property named model that holds your model before you perform the binding, or you can pass an optional model in the options as shown in the example above.
When binding to a view with a model, Backbone's validate method on the model is overridden to perform the validation. In addition, the model's isValid method is also overridden to provide some extra functionality.
Binding multiple views to same model
It is possible to bind several views to the same model. This is specially useful in UI structures where forms are made with components that share models.
When the model is validated all associated views with attributes from that model will validate its related elements.
It is also possible to unbind each view separately without affecting other bindings.
Binding to view with a collection
For this to work, your view must have an instance property named collection that holds your collection before you perform the binding, or you can pass an optional collection in the options as shown in the example above.
When binding to a view with a collection, all models in the collection are bound as described previously. When you are adding or removing models from your collection, they are bound/unbound accordingly.
Note that if you add/remove models with the silent flag, they will not be bound/unbound since there is no way of knowing the the collection was modified.
Unbinding
If you want to remove the validation binding, this is done with a call to Backbone.Validation.unbind(view). This removes the validation binding on the model, or all models if you view contains a collection, as well as removing all events hooked up on the collection.
Note that if you are binding to an optional model or collection, you must also specify this when unbinding: Backbone.Validation.unbind(view, {model: boundModel}).
Using model validation
The philosophy behind this way of using the plugin, is to give you an easy way to implement validation across all your models without the need to bind to a view. Of course, if you use this option the callbacks to update the view is not executed, since there is no way of knowing what view a model belongs to.
Validation mix-in
To add validation to your models, mix in the validation on the Model's prototype.
_.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
Using server validation
If you are using node.js on your server, you can also reuse your models and validation on the server. For this to work you
Related Skills
node-connect
338.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
83.4kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
338.0kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
83.4kCommit, push, and open a PR
