Search code examples
validationbackbone.js

How to prevent validate function call while calling model.save in backbone JS


I have a backbone view where I call model.save to create/updated date submitted in the form. Before calling the save I explicitly call model.isValid(true) to validate the form fields then I process the form data to make it ready for API expected format (by adding or modifying additional fields) and then make call to mode.save function which is again triggering validate function where the validations are getting failed due to the modified data. As I have already called the isValid function explicitly, I want to prevent the call again during save. How can I do it in backbone. Here is sample code.

    var data = Backbone.Syphon.serialize($(e.currentTarget).closest('form.my_form')[0]));   
    this.model.set(data);

    if(this.model.isValid(true)) {

                   data['metas'] = this.context.metaData;
                   data['metas'][0]['locale'] = this.parentObj.model.get('locale');

                   data['metas'][0]['name'] = data['name'];
                   delete data['name'];
                 }

                 var tempDynAttrs = [];
                 if(data['dynamicAttributes']){
                       $.each(data['dynamicAttributes'], function(index,obj) {
                           if(obj['attributeValue'] !== null && obj['attributeValue'] !== undefined ) {
                               tempDynAttrs.push({
                                    attributeName: obj['attributeName'],
                                    attributeValue: [obj['attributeValue']],
                                    locale: data['defaultLocale'],
                                    status: 'active'
                                });
                             } 
                       });
                   }
                 data['dynamicAttributes'] = tempDynAttrs;

                 this.model.save(data, {
                   url: this.model.url(),
                   patch: true,
                   success : function(model, response) {
                       $('#headerMessage').html('Data is updated successfully');
                   },
                   error : function(model, response) {
                        $('#headerMessage').html('Error updating data');
                   }
               });
} else {
    $('#formPanel').animate({
                 scrollTop: $('.has-error').first().offset().top-50
               }, 100);
     return false;
}

Solution

  • Try passing {validate:false} in the save options, like

    book.save({author: "Teddy"}, {validate:false});
    

    According to change log of version 0.9.10:

    Model validation is now only enforced by default in Model#save and no longer enforced by default upon construction or in Model#set, unless the {validate:true} option is passed.

    So passing {validate:false} should do the trick.