Backbone.validation not working on save

88 Views Asked by At

I have a simple model using the Backbone.Validations plugin.

var LocationModel = Backbone.Model.extend({
validation: {
     location_name: {
         required   : true,
         msg        : 'A name is required for the location'
    }
} // end validation
});

var test = new LocationModel();
test.url = 'http://link-goes-here';
test.save();

It appears that on the save event, it's going ahead and saving my empty model even though the attribute "location_name" is required?

1

There are 1 best solutions below

0
On BEST ANSWER

I just did a bunch of testing and the only way I could get it to consistently not send a request was by also creating defaults on the model:

var LocationModel = Backbone.Model.extend({
    defaults: {
        location_name: null
    },
    validation: {
        location_name: {
            required: true,
            msg: 'A name is required for the location'
        }
    } // end validation
});

var test = new LocationModel();
test.on('validated', function() {
    console.log(arguments);
});
test.url = '/echo/json';

test.save();

Here's a fiddle. If you comment out the defaults, it sends a request initially, even though the validated event is saying that it's invalid. And then fires validated again without sending the request.