Backbone 验证 return 属性名称

Backbone validation return attribute name

模型中:

 validation: {
        title: {
            required: true
        },
        body: {
            required: true
        }
    }

在视图中我调用:

this.parent.model.isValid(['title', 'body']);

这只是 return 我的 true/false,如何更改验证以获取无效的参数名称?

我不能一一传递属性,因为它可能很多。

覆盖验证函数http://backbonejs.org/#Model-validate

执行您想要的 wtv 过滤器和 return 您想要的 wtv 对象。

希望对您有所帮助

docs mate

中有解释

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);
});

在你的情况下(代码未经测试,我希望你明白):

this.parent.model. = Backbone.Model.extend({
      validate: function(attrs, options) {
        var errors= new Array;
        if (!attrs.title) {
          errors.push("Title is required");
        }
        if (!attrs.body) {
          errors.push("Body is required");          
        }
        if errors.length
            return errors;
      }
    });

this.parent.model.on("invalid", function(model, error) {
      alert(error);
    });


//You don't need to pass an attribute list
this.parent.model.isValid();

请注意,您会将错误数组(如果有)保留在 this.parent.model.validationError 以供稍后处理,因此您无需捕获模型 "invalid" 事件