Validate Subcollections in Backbone models

October 26th, 2012 by admin Leave a reply »

Backbone.js is an awesome library for Javascript development, and at some point in your application, probably close to the finishing point, you will want to validate your models and Backbone has provided a great function through that, find out more about that here: As I was adding validation to my models I had the need to validate my subcollections that were in my models and I just didn’t see a good way to do that besides sending up my subcollections via the posts or the save() method in backbone, which I don’t want to be doing until my main model is ready to be sent up.

I know its wrong or bad coding to be adding unvalidated models to your collections but in my situation it was necessary so I came up with a little method of validating those models, check out the snippet below:

validate: function (attrs) {
           if (attrs.Products.length == 0) {
                return "Please choose at least one product";
            } else {
                var error;
                var that = this;
                attrs.Products.each(function (prod) {
                    error = prod.validate(prod.attributes);
                if (error)
                    return error;

As you can see in the validate function of the main model it simply iterates over each ‘Product’ in the Products collection and calls validate on those products and if an error is thrown down in the product model it will bubble up to my main model and thus show the user the error. Its a simple solution that I kind of expected backbone to be able to handle for me but everybody out there just says to validate your model before it goes into the collection but there are situations where that just isn’t possible. I hope this helps someone out, have a great day!!


Leave a Reply