I am using Backbone’s validate function to guarantee Man to have an age property more than 18. Here is my code:
var Man = Backbone.Model.extend({
initialize : function(){
this.on("error",function(model,error){
alert(error);
});
},
validate : function(attrs,options){
if (attrs.age < 18){
return 'below 18';
}
}
})
var man = new Man({name : 'qian', age : 12});
But looking at the result it seems that validate doesn’t work.
In Backbone.js (prior to version
0.9.10),validateis called beforesaveas well as beforeset.You will get an alert error when you set invalid value.
Example –
agevalue is below 18 :EDIT
For Backbone.js version
0.9.10+there is an issue reported: Failed validation does not trigger error callback. Issue explanation says thatSo changing your code to:
And setting variable with
validateoption set totruewill trigger analert.