validate method inside Backbone Model not being called?

backbone.js, javascript, jquery

Solution

Model validation changed in Backbone 0.9.10:

Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the `{validate:true}` option is passed.

and note that

Model validation now fires invalid event instead of error.

So your code should be written as

var person = new Person({
    name: 'Lady Madonna',
    age: 23
});

person.on('invalid', function(model, error){
    console.log(error);
});

person.set('age', -55, {validate : true});

And a Fiddle http://jsfiddle.net/nikoshr/aUxdS/

Problem

Beginning to learn Backbone, trying to do some simple validation inside my Person Model but the validate method doesn't seem to be run when I set a new age. Can anyone explain where i may be going wrong on this? Don't want to move on with my learning until I get this right. JS ``` var Person = Backbone.Model.extend({ defaults: { name: 'John Doe', age: 30, occupation: 'working' }, validate: function(attrs) { console.log(attrs); if ( attrs.age < 0 ) { return 'Age must be positive, stupid'; } if ( ! attrs.name ) { return 'Every person must have a name, you fool.'; } }, work: function() { return this.get('name') + ' is working.'; } }); ``` Currently I am just getting and setting values in the console, so: ``` var person = new Person({ name: 'Lady Madonna', age: 23 }); person.on('error', function(model, error){ console.log(error); }); ``` When I set age to be a negative value the validate method doesn't take effect: ``` person.set('age', -55); ```

Original source