使用 Knockout 库,我编写了一个 ViewModel(主要基于他们的在线指导),它进行了一些验证。一切都很完美,除了...
1)一旦我的对话框启动,验证立即调用
2)我想将验证绑定到对话框按钮而不是输入框,并且仅在用户单击“添加新帐户”按钮时触发。
下面是我的 JSFiddle 的链接。感谢您提供的任何指导。
HTML
<a href="#" id="createAccount">Create New Account</a>
<div id="newAccount" title="New Account">
<p>
<span class="ui-state-highlight" data-bind='visible: accountName.hasError, text: accountName.validationMessage'> </span>
</p>
<form>
<fieldset>
<label for="name">Enter Account Name:</label><br />
<input type="text" id="accountName" data-bind='value: accountName, valueUpdate: "afterkeydown"' />
</fieldset>
</form>
</div>
视图模型
$("#newAccount").dialog({
autoOpen: false,
width: 450,
height: 300,
modal: true,
buttons: {
"Add New Account": function () {
// post data
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
$("#createAccount")
.click(function () {
$("#newAccount").dialog("open");
});
ko.extenders.required = function(target, overrideMessage) {
target.hasError = ko.observable();
target.validationMessage = ko.observable();
function validate(newValue) {
target.hasError(newValue ? false : true);
target.validationMessage(newValue ? "" : overrideMessage || "This field is required");
}
validate(target());
target.subscribe(validate);
return target;
};
function ViewModel(account) {
this.accountName = ko.observable(account).extend({ required: "An account name is required" });
}
ko.applyBindings(new ViewModel());
干杯,
克劳德