Does anyone have any advice or examples for doing validation with backbone.js and ruby on rails 2.x or 3.x?开发者_开发问答
One approach is to locate your error handling in a base model that you extend by assigning a default error handler. This error handler should handle both client-side and server errors display. Here's what the base model extension might look like:
Model = Backbone.Model.extend({
ui: Utils.UI,
initialize: function(attributes, options) {
options || (options = {});
_.bindAll(this, 'defaultErrorHandler');
this.bind("error", this.defaultErrorHandler);
this.init && this.init(attributes, options);
},
// Gets call for failures in validate and for server failures.
defaultErrorHandler: function(model, error) {
var errors;
if (_.isArray(error)) {
errors = error.join('<br/>');
} else {
// Server error; parse as needed into a displayable error.
}
this.ui.showError(errors);
}
});
then other models can extend and get this validation functionality. Here's a Session model which contains its client-side validation:
Session = Model.extend({
validate: function(attrs) {
var errors = []
if (_.isEmpty(attrs.email)) {
errors.push("Email can't be blank");
}
if (_.isEmpty(attrs.password)) {
errors.push("Password can't be blank");
}
return _.any(errors) ? errors : null;
}
});
You could also handle it all in the validate function since it gets called before a save and after a save where after the save it might be dealing with errors that have been parsed out of the server response.
Using the above approach, you need not specify an error function when you call the model's save function. It should be handled by the base functionality.
I've been using the Backbone.validations plugin with great success. It allows you to define your validations just like you do in Rails models.
var ValidatingModel = Backbone.Model.extend({
validate : {
name : {
required : true,
pattern : /[a-zA-Z]+/,
minlength : 3,
maxlength : 100
},
age : {
type: "number",
min: 0,
max: 200
},
email : {
type: "email"
},
homepage : {
type: "url"
},
occupation : {
in : [
"Lawyer",
"Doctor",
"Professor",
"Economist"
]
}
}
});
精彩评论