O'Reilly logo

Backbone.js Patterns and Best Practices by Swarnendu De

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Validating the data

In Backbone, validation is taken care of by the model.validate() method. By default, the Backbone.Model class doesn't have a validate() method on its own. However, the developers are encouraged to add a validate() method that gets called by the model every time an attribute is saved or set with validate: true passed. A copy of the attributes is sent to the validate() method with all the changed values. Let's look at a simple data validation:

var User = Backbone.Model.extend({ validation: { emailRegEx: /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/ }, defaults: { name: '', email: '' }, validate: function (attr) { if (attr.name.length === 0) { return 'Name is required'; } if (attr.email.length === 0) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required