Skip to content

Instantly share code, notes, and snippets.

@airhorns
Created January 9, 2011 00:46
Show Gist options
  • Select an option

  • Save airhorns/771286 to your computer and use it in GitHub Desktop.

Select an option

Save airhorns/771286 to your computer and use it in GitHub Desktop.
Potential Validations syntax
// A complete example.
var Post = Backbone.Model.extend({
validations: {
body: {
required: true, // Uses the built in validation methods
minLength: 100
},
title: {
// Pass multiple arguments to the validation function
lengthInRange: [10,100],
// Pass custom validation functions. Push errors into an array, Rails style.
capitalized: function(attr, errors) {
var c = attr.substr(0,1);
if(c !== c.toUpperCase()) {
errors.push("Capitalize the title properly please!");
}
},
// Overrride default error messages using last argument convention.
required: [true, "You can't have a post without a title, this custom but informative message says so!"]
},
// Author attribute just has one custon validation.
author: function(author, errors) {
if(!author.canPublish()) {
errors.push("Please publish this post as an author who is able to publish.");
}
},
// Whole model has validations, 'base' is a reserved attribute.
base: function(attrs, errors) {
if(!stars.aligned()) {
errors.push("A message about the whole model being invalid.");
}
}
}
});
// In progress implementation at http://github.com/hornairs/backbone
// Please leave feedback!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment