Search code examples
javascriptjquerybackbone.js

backbone validate method doesn't trigger in my case


I'm new to backbone.

var Person = Backbone.Model.extend({
  defaults: {
    name: '',
    age: 30,
    occupation: 'fireman'
  },
  validate: function(attrs) {
    console.log(attrs) // this won't trigger? since the model's attr changed;
  },
  run: function() {
    return this.get('name') + ' is running';
  }
})

var p = new Person({name:'James'});
p.set('age',25); 

I change the model's property but somehow I did not see the console. Why?


Solution

  • You need to tell the set method to validate by passing validate option. http://backbonejs.org/#Model-validate

    p.set({age: 25}, {validate: true});