我已经对“名字”实施了一个非常基本的必需验证,主要基于淘汰网站上建议的示例(http://knockoutjs.com/documentation/extenders.html ) 上建议的示例 - 实时示例 2:向可观察对象添加验证。
我的问题是我不希望在首次加载表单时触发验证。下面是我的代码
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<link href="Style.css" rel="stylesheet" />
</head>
<body>
<p data-bind="css: { error: firstName.hasError }">
<span>First Name</span>
<input data-bind='value: firstName, valueUpdate: "afterkeydown"' />
<span data-bind='visible: firstName.hasError, text: firstName.validationMessage'></span>
</p>
<p>
<span>Last Name</span>
<input type="text" data-bind="value: lastName, valueUpdate: 'afterkeydown'" />
</p>
<div data-bind="text: fullName" />
<script src="Scripts/jquery-2.0.3.js"></script>
<script src="Scripts/knockout-2.3.0.debug.js"></script>
<script src="script.js"></script>
</body>
</html>
var AppViewModel = function () {
var firstName = ko.observable().extend({ required: "Please enter First Name" }),
lastName = ko.observable(),
fullName = ko.computed(function () {
return firstName() + " " + lastName();
});
return {
firstName: firstName,
lastName: lastName,
fullName: fullName
};
};
ko.extenders.required = function (target, overrideMessage) {
//add some sub-observables to our observable
target.hasError = ko.observable();
target.validationMessage = ko.observable();
//define a function to do validation
function validate(newValue) {
target.hasError($.trim(newValue) ? false : true);
target.validationMessage($.trim(newValue) ? "" : overrideMessage || "This field is required");
}
//initial validation
validate(target());
//validate whenever the value changes
target.subscribe(validate);
//return the original observable
return target;
};
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);
您将在此链接http://jsfiddle.net/tCP62/22/上看到我面临的问题演示
请注意,我提供给演示的 JSFiddle 链接显示了问题 - 在“Chrome”中有效,在 IE 中无效。
请任何人都可以帮我解决这个问题。
问候, 安库什