Validation in Backbone Models

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?

Answers


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.


Need Your Help

Python JSON Decoder Error

python json irc twitch

I'm currently using a script that broadcasts to IRC when a specified Twitch TV Channels goes on Air.

It's too slow to show image sequence as a video in Flash Player

actionscript-3 flash flex loader

At first I'm a new Flex AS programmer. My need is the same as @Michael Pliskin Best way to show image sequence as a movie in Adobe AIR, but I need show image sequence to animate video in browser th...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.