Search code examples
javascriptbackbone.jsbackbone.validation.js

backbone.validation plugin. Validation doesn't work on model


I try to to use Backbone.validation plugin.
Here is a link to this plugin. https://github.com/thedersen/backbone.validation.

I want to start a validation, when I create a new model instance. Normally in Backbone should implement a validate function and then when we should pass {validate:true}

How achieve the same result with this plugin?

   //create picture instance in a controller 
    var model = new Picture({
            name: file.name,
            size: file.size, 
            type: file.type
     }, {validate: true} );
    

//Picture class
export default Backbone.Model.extend({
    defaults: {
        name: "",
        size: null, 
        type: ""
    },
    validation: {
        size: function (size) {
            if(size > this.MAX_FILE_SIZE;) {
                return this.onFileSizeError()
            }
            return '';
        },
        onFileSizeError() {
             //execute this when model size is wrong
        }

});

Solution

  • Problem solved

    So in a plugin documentation is information about validation on model without binding with a view.

    Using model validation

    The philosophy behind this way of using the plugin, is to give you an easy way to implement validation across all your models without the need to bind to a view. Of course, if you use this option the callbacks to update the view is not executed, since there is no way of knowing what view a model belongs to.

    Validation mix-in

    To add validation to your models, mix in the validation on the Model's prototype.

     _.extend(Backbone.Model.prototype, Backbone.Validation.mixin);

    So we can create a file with a base model which will be extend Backbone.Model.prototype. Now each new class should be extended by our class Model.

    From now we can use a validation.plugin on our instance