在模型中:
validation: {
title: {
required: true
},
body: {
required: true
}
}
我认为是:
this.parent.model.isValid(['title', 'body']);
这仅返回我的true / false,如何更改验证以获取无效的参数名称?
我不能一一通过属性,因为可能很多。
在docs伙伴中有解释
失败的验证会触发“无效”事件,并使用此方法返回的值在模型上设置validationError属性。
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
处,以便以后处理,因此您无需捕获模型上的“无效”事件