It is easy to bind to the ‘error’ event of an existing model, but what is the best way to determine if a new model is valid?
Car = Backbone.Model.extend({
validate: function(attributes) {
if(attributes.weight == null || attributes.weight <=0) {
return 'Weight must be a non-negative integer';
}
return '';
}
});
Cars = Backbone.Collection.extend({
model: Car
});
var cars = new Cars();
cars.add({'weight': -5}); //Invalid model. How do I capture the error from the validate function?
Validation logic can be triggered explicitly by calling the
validatemethod of your model. This will not, however, cause anerrorevent to be triggered. You can trigger an error event manually for a model by calling thetriggermethod.One way to achieve your desired behavior is to manually trigger the event in your initialization method: