user2483724
user2483724

Reputation: 2119

Backbone.js: How to get model validation error from collection.create

Trying to add a model using collection.create. I added validation on the model and it works in that when I try to create the model nothing happens. However neither the success or error callback is triggered, the page just sits there. How do I get the actual error back? (validation just returns a string like "this is wrong")

I believe the issue is that the error callback only fires on server returned errors. How do you catch validation errors from here then though?

self.collection.create({
     //attributes
   }, {
   success: function (model, response) {
       //this doesn't run
   },
   error: function (model, response) {
       //this doesn't run either
   }
});

Upvotes: 0

Views: 801

Answers (1)

StateLess
StateLess

Reputation: 5402

From the documentation

Returns the new model. If client-side validation failed, the model will be unsaved, with validation errors

var model = self.collection.create({
     //attributes
   }, {
   success: function (model, response) {
       //this doesn't run
   },
   error: function (model, response) {
       //this doesn't run either
   }
});

Now you can handle the error in 2 ways:
1) using events

model.on('invalid',function(){
  // error handling here
});


2) using flag

   if(model.validationError){
       // error handling here
        } 

Upvotes: 2

Related Questions