hookedonwinter
hookedonwinter

Reputation: 12666

Backbone.js: Add validation to every model

I'm having trouble wrapping my head around this, and would love some guidance.

I have an admin crud app where I would like to validate all models in a similar fashion. The code I'm using for validation works fine when I use it in a validate function:

var ModelName = Backbone.Model.extend({
    // ...
    validate: function (attrs) {
        // stuff happens
        return errors;
    }
});

However, I want to use the validation on every model, and don't want to repeat myself with the same code in every model.

How can I extend the Backbone Model to include this validate function on every model?

Upvotes: 0

Views: 213

Answers (2)

fguillen
fguillen

Reputation: 38832

Despite the great solution @ggozad has shown you always can move the validate logic to a shared function like:

var Utils = {}
Utils.validateSomething = function( attributes ){
  // stuff happens
  return errors;
}

var ModelName = Backbone.Model.extend({
  validate: Utils.validateSomething
});

You still have to replicate the validate line in every Class but I think is DRY enough.

Upvotes: 1

ggozad
ggozad

Reputation: 13105

You can do this easily by "subclassing", say for instance,

var Validatable = Backbone.Model.extend({
    validate: function (attrs) {
        // stuff happens
        return errors;
    }
});

var ModelOne = Validatable.extend({
   ...
});

var ModelTwo = Validatable.extend({
   ...
});

Alternatively, you still base on Backbone.Model and use _.extend directly.

Upvotes: 2

Related Questions