我想在將對象添加到可觀察對象之前驗證用戶輸入。例如,如果我有兩個字段,說數量和價格,在將對象添加到可觀察值之前,我想驗證用戶輸入。 我該如何實現這種行爲?輸入驗證後將對象添加到KnockoutJS
是我到目前爲止的代碼:
self.productPriceAdd = function() {
var newPrice = {
Quantity: self.newProductPriceEntry.Quantity(),
Price: self.newProductPriceEntry.Price(),
ProductBarcode: self.productPrices().Barcode
}
self.productPrices().ProductSalePrices().push(newPrice);
self.productPrices().ProductSalePrices(self.productPrices().ProductSalePrices());
self.newProductPriceEntry.Quantity(null);
self.newProductPriceEntry.Price(null);
}
的用戶界面看起來somethig這樣的:
所以用戶點擊Add按鈕後,兩個錯誤消息應該是顯示,每個空字段一個。
我的HTML代碼:
<!-- ko if: productPrices() -->
<div class="col-md-4">
<div class="panel panel-default">
<div class="panel-heading">
<h2 class="panel-title"><b data-bind="text: productPrices().Name"></b></h2>
</div>
<table class="table">
<tr>
<th>
@Html.DisplayName("Quantity")
</th>
<th>
@Html.DisplayName("Price")
</th>
<th></th>
</tr>
<tbody data-bind="foreach: productPrices().ProductSalePrices()">
<tr>
<td>
<b data-bind="text: Quantity"></b>
</td>
<td>
<b data-bind="text: Price"></b>
</td>
<td>
<a href="#" data-bind="click: $parent.productPriceRemove" class="btn btn-defaul">Remove</a>
</td>
</tr>
</tbody>
<tbody data-bind="with: newProductPriceEntry">
<tr>
<td>
<input type="number" class="form-control" data-bind="value: Quantity " placeholder="Quantity">
</td>
<td>
<input type="number" step="0.01" class="form-control" data-bind="value: Price " placeholder="Price">
</td>
<td>
<a href="#" data-bind="click: $parent.productPriceAdd" class="btn btn-defaul">Add</a>
</td>
</tr>
</tbody>
</table>
</div>
<a href="#" data-bind="click: productPriceSave" class="btn btn-defaul">Save</a>
我已經使用了Knockout-Validation,它顯示了相應的錯誤消息,但我仍然可以向observable變量添加無效對象,例如空字段。有什麼辦法來檢查是否有驗證錯誤,並防止添加無效的對象到observable? – sixfeet