使用扩展程序验证Knockout.js - 防止加载验证

时间:2013-07-19 10:07:06

标签: javascript validation knockout.js asp.net-web-api

我已经在“名字”上实施了一个非常基本的必需验证,主要是基于淘汰网站(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中不起作用。

请任何人帮我解决这个问题。

此致 Ankush

1 个答案:

答案 0 :(得分:3)

只需删除以下行,它就可以执行您想要的操作:

//initial validation
validate(target());

当您的页面加载时会调用required扩展程序,并且因为它包含上述调用,它会立即触发验证。下一行代码target.subscribe(validate);确保在observable更改值时触发它(如注释所述)。在这种情况下,这就是你所需要的一切。