Javascript 在主干模型/视图上处理更复杂的验证逻辑(必填字段等)的最佳方法?
主干网内置的Javascript 在主干模型/视图上处理更复杂的验证逻辑(必填字段等)的最佳方法?,javascript,backbone.js,marionette,backbone-events,Javascript,Backbone.js,Marionette,Backbone Events,主干网内置的validate()模型方法在非常简单的情况下运行良好,但在处理更复杂的验证逻辑(如必填字段)时,它很快就会崩溃。在模型上,我通常是这样处理属性验证的: validate: function (attrs) { var invalid = [], dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/, timeRegex = /^(\d{2}):(\d{2})$/, isoDateTimeRegex
validate()
模型方法在非常简单的情况下运行良好,但在处理更复杂的验证逻辑(如必填字段)时,它很快就会崩溃。在模型上,我通常是这样处理属性验证的:
validate: function (attrs) {
var invalid = [],
dateRegex = /^(\d{2})\/(\d{2})\/(\d{4})$/,
timeRegex = /^(\d{2}):(\d{2})$/,
isoDateTimeRegex = /^(\d{4})-(\d{1,2})-(\d{1,2})T(\d{2}):(\d{2}):(\d{2})$/;
if (_.has(attrs, "chosenScheduleDate") && !dateRegex.test(attrs.chosenScheduleDate)) {
invalid.push("chosenScheduleDate");
}
// ...some more validation rules
if (invalid.length > 0) {
return invalid;
}
},
然后,在视图中,使用新的ishinvalid
事件过滤无效属性:
modelEvents: {
"invalid": "invalidateAttributes"
},
// ...other code
invalidateAttributes: function (model, error) {
if (_.contains(error, "chosenScheduleDate")) {
this.unsetModelAttributes("chosenScheduleDate", "chosenScheduleOpenTime", "scheduleOpenTime");
this.statusNotification.show.call(this, localizedText.displayText.theSelectedDateIsInvalid, "error");
this.ui.chosenScheduleDateInput.addClass("text-input--error");
}
},
这可能导致一个相当长的invalidateAttributes方法,特别是在验证6+模型属性时。此外,这还没有考虑到必填字段的概念,我通过执行不愉快的has()
检查来处理此问题:
if (this.model.has("scheduleOpenTime")) {
$.when(this.parent.saveAppointment.call(this))
.done(function () {
// set a new attribute on the model that represents the successfully-persisted datetime value
that.model.set("savedScheduleOpenTime", that.model.get("scheduleOpenTime"));
that.renderAppointmentForm();
});
}
然后,当属性在尝试设置期间无效时,必须unset()
属性,实际上只允许在任何给定时间模型上存在有效属性
是否有更好、更优雅的方法来处理主干模型上更复杂的验证,包括必填字段?我真的更喜欢一种简单的方法,不使用像主干验证插件之类的重量级解决方案。很想看看其他人在使用什么样的模式。Addy Osmani的主干基础知识书中有关于模型属性验证的。使用将是我的第一个建议,因为它可以很好地处理必填字段,但您明确提到要避免这种情况。Addy对该主题的讨论涉及到一些备选方案,包括插件,或者专注于验证表单而不是模型。Addy Osmani的主干基础知识书中有关于模型属性验证的。使用将是我的第一个建议,因为它可以很好地处理必填字段,但您明确提到要避免这种情况。Addy对该主题的讨论涉及到一些备选方案,包括插件,或者专注于验证表单而不是模型