使用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());
干杯,
克劳德
答案 0 :(得分:1)
您需要对代码进行两次修改:
validate(target());
。这只是初步验证。open:function(){
ko.applyBindings(new ViewModel());
}
请检查此 Working Demo