Validation with backbone.js and Ruby on Rails

Does anyone have any tips or examples for checking with backbone.js and ruby ​​on 2.x or 3.x rails?

+6
source share
2 answers

I use the Backbone.validations plugin with great success. It allows you to define your checks in the same way as 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" ] } } }); 
+9
source

One approach is to find your error handling in the base model that you are extending by assigning a default error handler. This error handler should handle both client and server errors. Here's what the base model extension looks 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 expand and receive this verification function. Here is a session model that contains 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 can also handle all this in the validate function, since it is called before saving and after saving, where after saving it can deal with errors that were analyzed from the server response.

Using the approach described above, you should not specify an error function when calling the model save function. It must be handled by basic functionality.

+12
source

Source: https://habr.com/ru/post/890070/


All Articles