model.validate

validatemodel.validate(attributes, options)
This method is left undefined and you're encouraged to override it with any custom validation logic you have that can be performed in JavaScript. By default save checks validate before setting any attributes but you may also tell set to validate the new attributes by passing {validate: true} as an option.
The validate method receives the model attributes as well as any options passed to set or save. If the attributes are valid, don't return anything from validate; if they are invalid return an error of your choosing. It can be as simple as a string error message to be displayed, or a complete error object that describes the error programmatically. If validate returns an error, save will not continue, and the model attributes will not be modified on the server. Failed validations trigger an "invalid" event, and set the validationError property on the model with the value returned by this method.

var Chapter = Backbone.Model.extend({
  validate: function(attrs, options) {
    if (attrs.end < attrs.start) {
      return "can't end before it starts";
    }
  }
});

var one = new Chapter({
  title : "Chapter One: The Beginning"
});

one.on("invalid", function(model, error) {
  alert(model.get("title") + " " + error);
});

one.save({
  start: 15,
  end:   10
});

"invalid" events are useful for providing coarse-grained error messages at the model or collection level.

doc_Backbone
2016-04-17 12:21:44
Comments
Leave a Comment

Please login to continue.