My validate function is not getting called in the code below:-
var Vehicle = Backbone.Model.extend({
color: 'green',
validate: function (attrs) {
var validColors = ['white', 'red', 'blue', 'yellow'];
var colorIsValid = function (attrs) {
if (!attrs.color) return true;
return _.contains(validColors, attrs.color);
}
if(!colorIsValid(attrs)) {
return "color must be one of: " +validColors.join(",");
}
}
});
var car = new Vehicle();
car.on('error', function (model, error) {
console.log(error);
});
console.log(car.get('color'));
car.set('color', 'muave');
Please see fiddle
http://jsfiddle.net/vineet85/Fa8jr/5/
Can someone tell me why the validate function is not getting called?
In Backbone.js
validateis called automatically onsavebut not onset.If you want validations to run when setting a value you will need to use the
validateoption. e.g.See http://backbonejs.org/#Model-validate
The
errorevent is triggered when an error occurs, typically on the server, when trying to save the object. See http://backbonejs.org/#Events-catalogIf you want to catch validation failures try handling the
invalidevent: