2013-07-17 73 views
-1

使用Knockout庫,我編寫了一個ViewModel(主要基於他們的在線指導),它做了一些驗證。一切正常,除了完美...幫助敲除驗證

1)驗證立即調用一次我的對話框啓動

2)我想驗證到對話框按鈕,而不是輸入框綁定,並將它只會引發當用戶點擊「添加新帳戶」按鈕時。

下面是我的JSFiddle的鏈接。感謝您提供的任何指導。

http://jsfiddle.net/9PV7X/

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()); 

乾杯,

克勞德

回答

1

你需要做你的代碼中有兩處修改:

  1. 爲了防止驗證立即調用一次對話啓動只是刪除或註釋此行validate(target());。這只是一個初始驗證。
  2. 應用模型綁定,當你打開你的對話框,你不需要申請,如果對話框沒有打開:

這樣

open:function(){ 
    ko.applyBindings(new ViewModel()); 
} 

查收這個Working Demo

+0

感謝您的迴應。當對話框第一次加載時,錯誤消息被抑制,但點擊添加新帳戶按鈕時驗證不會觸發。想法? – mynameisneo

+0

@mynameisneo我更新了我的jsfiddle以點擊「添加新帳戶」按鈕進行驗證。 –

+0

再次感謝您的幫助:) – mynameisneo