我已经开始使用带有http://ericmbarnard.github.com/Knockout-Validation/验证引擎的淘汰赛 js 验证,但我不清楚如何执行以下操作:
1)假设我想根据条件设置所需的特定字段。我怎么做?例如
this.Username = ko.observable().extend({ required: true }); // 仅当 this.UserType = 2 等时才使 required = true...
2) 我在正在验证的字段旁边触发了验证消息。我只想在该字段旁边显示一个“*”,并在页面底部的验证摘要字段中显示错误消息。所有验证错误都应显示在那里。怎么做?
3) 在表单验证通过之前,要避免表单提交。现在,我收到验证错误消息,但表单仍然被提交。所以我想我做错了什么。以下是我的代码:
$(document).ready(function () {
var model;
// enable validation
ko.validation.init();
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/GetData',
async: false,
data: "{ }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, status) {
model = new ViewModel(result);
ko.applyBindings(model);
},
error: GetDataError
});
$('#submit').click(function () {
var data = ko.toJS(model);
delete data.Vehicles;
delete data.CopyWeeks;
delete data.SetupTotal;
delete data.CloseTotal;
var mappedItems = ko.utils.arrayMap(data.DailyItemList, function (item) {
delete item.Add;
delete item.Delete;
return item;
});
data.DailyItemList = mappedItems;
$.ajax({
type: "POST",
url: SERVER_PATH + '/jqueryservice/DataAccessService.asmx/ProcessData',
async: false,
data: ko.toJSON(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result, stat) {
alert(success);
return false;
},
error: function (e) {
alert(e);
}
});
});
});
在此先感谢您的帮助。
编辑:我已经看到我可以按如下方式设置验证配置:ko.validation.configure({ decorateElement : false, errorMessageClass: 'errorMsg', insertMessages : false, parseInputAttributes : true, messageTemplate: 'sErrorMsg' }); ko.validation.init();
但我不确定如何定义我的错误消息模板'sErrorMsg'