Question

I am following these https://tutsplus.com/course/connected-to-the-backbone/ lectures to learn backbone and it came into my knowlege that validate() function (if exists) is called whenever we set the value of any variable inside that model. I have written this model:

var PersonModel = Backbone.Model.extend({

    defaults: {
        name: 'Kamran Ahmed',
        rollNo: '1224',
        email: 'kamranahmed.se@gmail.com'
    },

    validate: function (attrs){
        if ( !attrs.name ) {
            return 'You must provide a name';
        }
        if ( attrs.rollNo < 0) {
            return 'Roll Number must be positive';
        }
    }
});

And I am trying the following:

var person = new PersonModel();
person.set('rollNo', -100) // trying to violate the validation rule

But it never validates i.e. the value -100 is still being assigned to the rollNo. Plus it keeps returning the whole object when I do person.set('rollNo', -100) whereas it should return false as the validation rule is being violated. What am I doing wrong here? Why is the validation not being performed?

Was it helpful?

Solution

From the documentation:

 By default validate is called before save, but can also be called before set if 
 {validate:true} is passed. 

So you need to use it like:

person.set({'rollNo':-100},{validate:true})

You can read up on validate for a Backbone.Model.

As a side note: It appears that tutorial is for Backbone 0.9.2, while the current version is 1.1.0. Consider finding an up-to-date tutorial, or read the Change Log.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top