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({
va
Validation logic can be triggered explicitly by calling the validate
method of your model. This will not, however, cause an error
event to be triggered. You can trigger an error event manually for a model by calling the trigger
method.
One way to achieve your desired behavior is to manually trigger the event in your initialization method:
Car = Backbone.Model.extend({
initialize: function () {
Backbone.Model.prototype.initialize.apply(this, arguments);
var error = this.validate(this.attributes);
if (error) {
this.trigger('error', this, error);
}
},
validate: function(attributes) {
if(attributes.weight == null || attributes.weight <=0) {
return 'Weight must be a non-negative integer';
}
return '';
}
});