Mark
Mark

Reputation: 5088

Using backbone-validation.js on a model without views

I want to use backbone-validation to validate a model as it's being fetched from the server. This model doesn't have a view - it simply contains the user's permissions. Every example I have seen of backbone-validation.js requires a model to have a view e.g.:

    var Model = Backbone.Model.extend({
        validation: {
            name: {
                required: true
            }
        }
    });
    this.model = new Model();
    this.view = new Backbone.View({model: this.model});
    Backbone.Validation.bind(this.view);

But how do I use this plugin without having to pass the model into a Backbone view?

Upvotes: 0

Views: 126

Answers (1)

garethdn
garethdn

Reputation: 12351

If you don't want to bind a view try something like:

var Model = Backbone.Model.extend(_.extend({},  

  Backbone.Validation.mixin, {

    validation: {
      name: {
        required: true
      }
    }
  }

));

this.model = new Model();

Or if you would prefer to have this behaviour across all of your models use:

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

Upvotes: 2

Related Questions