Backbone.Validation banner
addyosmani addyosmani

Backbone.Validation

Development community

Description

[Deprecated] A validation plugin for Backbone.js

Installation

This entry records only its repository, not the path inside it, so there is no exact command to give. Open the source below and copy the folder into ~/.claude/skills/, or the file into ~/.claude/agents/.

README

Backbone.validation by Thomas Pedersen is a useful extension to Backbone which allows us to easily add complex validation rules to our Backbone models. You might be wondering how this extension differs from the out-of-the box approach to writing validation rules, so let's briefly review what we learned in the basics section.

Backbone models support a ```.validate()``` method for adding validation rules to a model, which is undefined unless we override it. If the model and attributes we're using pass our validation rules, ```validate()``` will return nothing, otherwise it can return an error of our choice. Below we can see an example of some simple validation against a Photo model's ```src``` attribute.

var Photo = Backbone.Model.extend({
  validate: function(attrs) {
    if (src === "") {
      return "source can't be empty!";
    }
  }
});

var one = new Photo({
  src : ""
});

one.bind("error", function(model, error) {
  alert(model.get("src") + " " + error);
});

one.set({
  caption: "this is a photo"
});

Todo: differences.

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.

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. If you want to provide a custom error message when using one of the built-in validators, simply define the `msg` property with your message.

Example

var SomeModel = Backbone.Model.extend({
  validation: {
    name: {
	  required: true,
	  msg: 'Name is required'
	},
    age: