-
-
Save netzpirat/1212648 to your computer and use it in GitHub Desktop.
Backbone Model Validation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_.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