Lukasz Migut
Lukasz Migut

Reputation: 192

Backbone model validation doesn't reject an invalid value

Why doesn't this simple example work:

var Person = Backbone.Model.extend({
    defaults: {
      title: 0  
    },

    validate: function(atts, options){
        if(atts.title < 0) {
            return console.log('tekst');
        }
    }

});

var person1 = new Person();
person1.on('invalid',function(model,error){
    alert(model.get('title') +error );
});

When I set an incorrect value with person1.set({title: -1},{validate: true}), the console returns an error message but the model is still changed to -1.

Upvotes: 1

Views: 104

Answers (1)

David Sulc
David Sulc

Reputation: 25994

From the documentation:

If the attributes are valid, don't return anything from validate; if they are invalid, return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically.

You need to return a value, not just have a return statement. Try this:

validate: function(atts, options){
    if(atts.title < 0) {
        return "can't be negative!";
    }
}

Upvotes: 1

Related Questions