Josh Earl
Josh Earl

Reputation: 18351

Backbone.js model validate method fails to fire

I'm trying to understand how Backbone.js model validation works, but I'm seeing some odd inconsistencies. In one place in my app, the validate method is getting called as expected. In another place, however, Backbone.js seems to be passing in a { silent: true } object to the validator, even though I don't want it to.

Here's a jsFiddle that illustrates the issue. The validate method should be called When the Copy buttons are clicked or the values change, but when I step through the code it's clear that the _validate function is being passed the { silent: true } option.

What am I missing?

Update: Figured out what was going on here. I created this jsFiddle originally to replicate an issue I was having that was actually the opposite of this question--I was trying to add an empty model to a collection and validation was firing and preventing me from doing so. When I made the Fiddle, though, it worked as I wanted my app to work. Validation wasn't firing when an empty model was added. I couldn't figure out the difference.

Turns out I was using Backbone.js 0.9.0 in my application and version 0.9.1 in my jsFiddle. Jeremy made changes to validation in 0.9.1 to make it work the way I wanted it to work in my app (see this issue on GitHub). Mystery solved.

Upvotes: 2

Views: 1993

Answers (2)

tkone
tkone

Reputation: 22728

Backbone specifically does not call _validate when you're making a new model.

Jeremy suggests that you do:

var mymodel = new MyModel();
mymodel.set({params});

Here's our exchange on github: can't override silent:true

Upvotes: 3

Upgradingdave
Upgradingdave

Reputation: 13056

From the Backbone docs, it seems you have to either call set or save on the model in order for validate to trigger.

I updated the jsfiddle so that set is called, and the now the validation function gets triggered:

http://jsfiddle.net/J3uuH/12/

Upvotes: 1

Related Questions