Skip to content

Instantly share code, notes, and snippets.

@mikeolivieri
Created September 11, 2011 16:08
Show Gist options
  • Save mikeolivieri/1209762 to your computer and use it in GitHub Desktop.
Save mikeolivieri/1209762 to your computer and use it in GitHub Desktop.
Backbone Model Validation
_.extend(Backbone.Model.prototype, Backbone.Events, {
errors: [],
validate: function (attrs) {
//reset
this.errors = [];
var model = this;
for (attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
//get valiators from attribute
var validators = _.select(this.validation, function(validator) {
return validator.attr == attr;
}, model);
_.each(validators, function(v) {
var validator = global.Validators[v.validator];
var result = validator.validate(attrs[attr], v);
if (!result) {
//only add one message for a property at a time
var existingAttrError = _.any(model.errors, function(e) {
return e.attr == v.attr;
}, model);
if (!existingAttrError) {
model.errors.push({ attr: v.attr, error: (v.message || v.attr + validator.message) });
}
}
}, model);
};
}
if (_.any(this.errors)) { return this.errors; };
},
hasErrors: function () {
return _.any(this.errors);
}
});
global.Validators = {
required: {
message: " can't be blank",
validate: function (value, args) {
return !_.isEmpty(value);
}
},
minLength: {
message: ' does not meet required length',
validate: function (value, args) {
return value.length > args.minLength;
}
},
email: {
message: ' must be an email address',
validate: function (value, args) {
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
return reg.test(value);
}
}
};
//usage
Model = Backbone.Model.extend({
validation: [
{ attr: "Name", validator: "required" }
]
});
var model = new Model();
model.bind("error", function(model, errors) { });
model.save({Name:""});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment