2013-07-19 43 views
5

我基於敲除網站上建議的示例(http://knockoutjs.com/documentation/extenders.html)實現了對「名字」的非常基本的必需驗證 - 現場示例2:將驗證添加到可觀察對象。使用擴展程序進行Knockout.js驗證 - 防止加載驗證

我的問題是,我不希望第一次加載窗體時激發驗證。下面是我的代碼

<!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鏈接到演示顯示了問題 - 在「鉻」的作品並且在IE中不起作用。

請任何人都可以幫我解決這個問題。

問候, Ankush

回答

3

剛剛擺脫以下行的,它應該做你想要什麼:

//initial validation 
validate(target()); 

required擴展被調用時,你的頁面加載,因爲它含有上述調用,它會導致驗證立即觸發。代碼target.subscribe(validate);的下一行確保在可觀察的更改值(如註釋所述)時觸發它。這就是你需要的全部內容。

+0

非常感謝你......我只是無法看到它的事情的大計劃...昨天花了大約4小時,並在發佈到堆棧溢出之前4個小時toady。但是,嘿,你做了我的一天。再次感謝你。 –

+0

現在我有另一個問題。我想在保存按鈕單擊時調用驗證,以使出現錯誤的控件突出顯示。基於上述,我可以在保存之前調用「驗證」並檢查「hasError」屬性。然而,如果我對「firstName」有兩個驗證 - 說「必需」,那麼firstName應該以「A」開始,並且有另一個擴展器。在這種情況下,是否必須在每個擴展器上以不同方式命名驗證方法,併爲每個需要驗證的observable調用所有驗證方法?很感謝任何形式的幫助。 –